2010-12-08 11 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

:이 기능을 사용하는 경우

은주의해야합니다. 당신이 그들을 사용한다면주의하는 것이 : strtok에 의해 반환 된 포인터가 라인 어레이에 색인되기 때문에

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

그래서 당신은 각 단어에 대한 새로운 메모리를 할당해야합니다.

는 최선의 코드를 변경하여 예시 :

... 
    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 

을 주목하는 각 줄의 첫 번째 단어에 대한 포인터는 동일합니다.