我是 C 语言新手。我需要知道如何请求用户输入(可以是任意数量的单词),然后将字符放入数组中。
我知道这个问题应该不难回答,但 Google 只是让我感到困惑。
提前致谢
最佳答案
如果我正确理解你的问题,你需要的是读取一些未知大小的用户输入,从而将这些信息存储到一个 char 数组中,对吗?如果是这种情况,一种可能的解决方案是使用一个 char 数组,将其分配给默认的固定大小,这会动态地动态重新分配其大小。
循环输入的字符后,在验证未达到 EOF 的同时,应将字符附加到数组中。然后,技巧是检查数组是否足够大以容纳用户输入的字符。如果没有,则必须重新分配数组的大小。
解决方案的示例实现可能如下所示:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int len_max = 128;
unsigned int current_size = 0;
char *input = malloc(len_max);
current_size = len_max;
printf("\nEnter input:");
if(input != NULL) {
int c = EOF;
unsigned int i = 0;
// Accept user input until hit EOF.
while (( c = getchar() ) != EOF) {
input[i++] = (char)c;
// If reached maximize size, realloc size.
if (i == current_size) {
current_size = i + len_max;
input = realloc(input, current_size);
}
}
// Terminate the char array.
input[i] = '\0';
printf("\nLong String value:%s \n\n",input);
// Free the char array pointer.
free(input);
}
return 0;
}
就性能而言,我不确定这可能是最好的解决方案,但我希望这可以帮助您解决问题。
亲切的问候 〜E.
关于c - 用户输入并插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868370/