2012-03-21 63 views
0
#define HISTORY_SIZE 50 
#define INPUT_SIZE 512 /*Max input size*/ 
char input[INPUT_SIZE]; /*Holding user input globaly*/ 
char* input_history[HISTORY_SIZE]; 

这是IM存储在输入我的输入,并想保存它的一个副本如何以input_historyC:获取用户输入,存储,延续着则显示过去50个输入

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]); 

我一直坐在努力工作,这一点对于年龄和不能似乎看到我去错了,也许是一双新的眼睛会注意到一些愚蠢的错误?

Basicly我想用

fgets(input,INPUT_SIZE,stdin) 

然后它的副本存储成char * input_history ,然后可以将其打印出来以后拿用户输入。

很简单。

+0

定义“不起作用”。 – cnicutar 2012-03-21 11:38:28

回答

3

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

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

或许:

input_history[currentHistorySize] = strdup(input); 

你应该还记得释放他们时,即可大功告成。

1

代替

input_history[currentHistorySize++] = input; 

使用

sprintf(input_history[currentHistorySize++],"%s",input); 

假设input_history被初始化。
但是,这并不关心input的大小小于或等于input_history[x]的容量。这是由你来检查。

+0

假设input_history已初始化 – UmNyobe 2012-03-21 11:41:10

+0

@UmNyobe当然是。我在答案中加了你的笔记。谢谢 – Saphrosit 2012-03-21 11:44:37

3

一个问题肯定是在这里:

input_history[currentHistorySize++] = input; 

最终,所有的历史将参照相同的内存位置,这是input 创建一个新的字符数组和复制输入进去,然后引用新阵列。

1

这是一个指针赋值,而不是一个字符串拷贝:

input_history[currentHistorySize++] = input; 

导致input_history所有元素指向input

你可以使用strdup()复制字符串:

input_history[currentHistorySize++] = strdup(input); 

malloc()strcpy()。当不再需要时记得free()的元素input_history