C:获取用户输入,存储,继续然后显示最后 50 个输入

标签 c string io copy

#define HISTORY_SIZE 50
#define INPUT_SIZE 512   /*Max input size*/
char input[INPUT_SIZE];  /*Holding user input globaly*/
char* input_history[HISTORY_SIZE];

这就是我如何将我的输入存储到 input,并希望将它的副本存储到 input_history

 void addToHistory()
 {
/*input_history[currentHistorySize++] = strtok(input,"\n");*/
input_history[currentHistorySize++] = input;
printf("ADDEDTOHISTORY: %s \t\t %d \n", input_history[(currentHistorySize- 1)],currentHistorySize);

 }

但是当我去打印出来时,它不起作用....

/*strcpy(input,input_history[currentHistorySize-2]);
printf("LAST INPUT, %s \n %s \n \n", input,input_history[currentHistorySize-2]);*/

printf("0: %s \n ", input_history[0]);
printf("1: %s \n ", input_history[1]);
printf("2: %s \n ", input_history[2]);

多年来我一直坐着尝试解决这个问题,但似乎看不出哪里出了问题,也许一双新眼睛会发现一些愚蠢的错误?

基本上我想接受用户输入使用

fgets(input,INPUT_SIZE,stdin)

然后将它的副本存储到 char* input_history 然后可以稍后打印出来。

非常简单。

最佳答案

最有可能的问题是您实际上并没有复制字符串,您只是在复制指针(字符串的地址)。试试这个:

input_history[currentHistorySize] = malloc(strlen(input) + 1);
strcpy(input_history[currentHistorySize], input);
currentHistorySize++;

或者也许:

input_history[currentHistorySize] = strdup(input);

您还应该记得在完成后释放它们。

关于C:获取用户输入,存储,继续然后显示最后 50 个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803823/

相关文章:

c - 在 C 中打印 ASCII

java - 使用java查找c文件中的宏变量

c - QuickSort 无法正确排序

scala - 如何将字符串写入 Scala Process?

java - 扫描仪在 Mac OSX 终端中无法正常工作

io - Flutter:写入文件的权限被拒绝

c - 将内联函数放在 C 头文件中是错误的吗?

java - 如何访问 Java 中每个循环的下一个元素?

python - 字符串中替换的条件

bash - 从 bash 映射中检索时如何区分 null 和空字符串