2012-03-21 10 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]; 

これは、入力にして、私の入力を保存し、そのコピーを保存したいイムでinput_historyする方法ですC:、ユーザー入力を取得、保存、continueingその後、表示の最後の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]); 

アイブ氏は、年齢のためにこれをうまくしようとして座ってとカントは、イムが間違って行く場所を確認するように見える、多分新しい目のペアがわかります....仕事doesntのいくつかの愚かな間違い?

私は

fgets(input,INPUT_SIZE,stdin) 

を使用して、ユーザーの入力をしたいBasiclyは、その後のchar *のinput_history にそれのコピーを保存し、後でそれをプリントアウトすることができます。

非常に単純です。代わりにinput_historyが初期化されると仮定すると

input_history[currentHistorySize++] = input; 

使用

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

+0

「動作しません」と定義します。 – cnicutar

答えて

3

実際には文字列をコピーしていないという問題があります。ポインタ(文字列のアドレス)をコピーするだけです。代わりにこれを試してみてください:

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

または多分:

input_history[currentHistorySize] = strdup(input); 

あなたはまた、あなたが完了したら、それらを解放するために覚えておいてください。inputinput_historyポインティングのすべての要素をもたらす

input_history[currentHistorySize++] = input; 

1


ただし、これはinputのサイズがinput_history[x]の容量以下であることには注意しません。確認するのはあなた次第です。ポインタ上に読むinput_history[currentHistorySize++] = input;

+0

input_historyが初期化されていると仮定します。 – UmNyobe

+0

@UmNyobeはい、もちろんです。答えにあなたのメモを追加しました。ありがとう – Saphrosit

3

一つの問題はここに間違いである:

input_history[currentHistorySize++] = input; 

は、最終的にすべてのあなたの歴史は、その後、新しいchar配列を作成し、それに入力をコピーinput で同じメモリ位置を参照しようとしています新しい配列への参照。

1

これは、ポインタ代入ではなく、文字列のコピーです。

あなたは、文字列をコピーするstrdup()を使用することができます。

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

またはmalloc()strcpy()。必要がなくなった場合はfree()の要素をinput_historyに覚えておいてください。

関連する問題