2012-03-21 64 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