2010-12-08 10 views
0

私はプログラムを作成しました。テキストファイルからリンクされたリストに単語単位でデータを取り込みます。しかし、単語をリストする際に問題があります。 '男はstrtok' からリンクリストの表示

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct list 
{ 
    char *data; 
    struct list *next; 
} node; 

int main() 
{ 
    int i; 
    char *word = NULL; 
    char line[1000]; 
    node *root,*temp; 

    root = (node *) malloc(sizeof(node)); 
    temp = root; 
    FILE *f = fopen("test.txt","r"); 
    while (fgets(line, sizeof(line), f)) 
     for (word = strtok(line, " "); word; word = strtok(NULL, " ")) 
     { 
      temp->data = word; 
      temp->next=(node *) malloc(sizeof(node)); 
      temp=temp->next; 
     } 
    fclose(f); 
    temp =root; 
    for(i=0; i<10; i++) 
    { 
     printf("%s\n",temp->data); 
     temp=temp->next; 
    } 
    return 0; 
} 
+0

ヘルプが必要な場合は、問題の内容を明記する必要があります。しかし、それが私だったら、リストの解析と構築が正しいことを確認したいと思います。リスティングよりも問題の可能性が高いと思われます。 –

+1

彼は各行の行配列を再利用しているようです。だから、彼はすべてのことが正しく働いていれば、最後の行から彼の言葉を見るだけです。 –

+0

"for(i = 0; i <10; i ++)"のために10語しか表示されません。代わりに "while(temp)"にする必要があります。そのためには、リストはヌルで終了する必要があります。したがって、メインループでは、 "temp-> next-> next = 0;"を追加します。 mallocの直後。 –

答えて

3

:これら の機能を使用する際に

は注意が必要です。あなたがそれらを使用する場合、ノート その:

* These functions modify their first argument. 
    * These functions cannot be used on constant strings. 
    * The identity of the delimiting character is lost. 

だから、はstrtokによって返されたポインタがラインアレイにインデックス付けされているので、単語ごとに新しいメモリを割り当てる必要があります。

これは最高にコードを変更することによって示されている:

次の入力で実行する
... 
    while (fgets(line, sizeof(line), f)) { 
    printf("%s\n",line); 
    for (word = strtok(line, " "); word; word = strtok(NULL, " ")) { 
     printf("%p\n",word); 
     temp->data = word; 
... 

check default for switches 
throw stmts to exit node 

は、次のように出力されます

check default for switches 

0x7fff94e0bf70 
0x7fff94e0bf76 
0x7fff94e0bf7e 
0x7fff94e0bf82 
throw stmts to exit node 

0x7fff94e0bf70 
0x7fff94e0bf76 
0x7fff94e0bf7c 
0x7fff94e0bf7f 
0x7fff94e0bf84 
throw 
stmts 

t 
throw 
stmts 
to 
exit 
node 

ていることに注意してください各行の最初の単語のポインタは同じです。

関連する問題