-1
텍스트 파일을 입력으로 사용하고 각 단어가 나오는 횟수를 출력하는 프로그램을 작성하고 있습니다. 이렇게하려면 연결된 목록을 사용하고 있지만 목록을 인쇄 할 때마다 각 줄의 마지막 단어 만 인쇄됩니다. 아래 코드는 각 단어를 목록에 추가하는 방법을 보여줍니다.연결된 목록은 텍스트 파일 줄의 마지막 단어 만 인쇄합니다.
while(fgets(line, sizeof(line), fp)){
LIST *node = malloc(sizeof(LIST));
token = strtok(line,delim);
while(token!=NULL){
if(search(head,token)){
node->count += 1;
}
else{
node->string = strdup(token);
node->count = 1;
node->next =NULL;
}
token = strtok(NULL, delim);
}
if(head == NULL){ current = head = node; }
else { current = current->next = node; }
}
줄 초기화는 다음과 같습니다. char * line [128]; search()는 단어가 이미 목록에 있으면 true를 반환하고 그렇지 않으면 false를 반환하므로 단어가 있으면 count가 증가합니다. 여기 와 나는 인쇄되는 경우 : 예를 들어
for(current = head; current ; current=current->next){
current->string = strtok(current->string,"\n");
printf("%-10s | %2d\n",current->string,current->count);
}
, 텍스트를 사용하는 경우 :
mary had a little lamb
its fleece was white as snow
and every where that mary went
the lamb was sure to go
어린 양, 눈, 간,
어쩌면'전류 -> 문자열 = strtok를 ("n \"전류> 문자열) : 다음과 같이
또한 링크 된 목록을 간소화 할 수 있습니다. – wildplasser여기에 몇 가지 논리적 인 오류가 있습니다. 'search'는 무엇을 반환합니까? 발견 된 노드 또는 NULL? 단어를 찾았을 때, 왜 발견 된 노드의 수 대신에'노드'에서'count'를 증가시키고 있습니까? 또한, 어디에도 목록에 추가하는 것을 보지 못합니다. – MFisherKDX
@wildplasser는 이것을 시도했지만 여전히 똑같은 행동을합니다. 제 첫 번째 while 루프와 관련이 있고 목록에 요소를 추가하는 방법이 있다고 생각합니다. – mcech