#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/