###前提・実現したいこと
単語の線形リストを作成し、同じ単語には1つのstruct word構造体を用い、単語の出現回数を数える。そして、出現単語を辞書順に並べ替える。
合っているかはわからないですが、一応単語の出現回数を数えるところまではできました。しかし、辞書順に並べ替えるときにうまくいかないので助言をいただきたく質問しました。まだ、始めたばかりですのでソースコードが見にくいかもしれませんが、宜しくお願いします。
あと、こうした方が良い、などの助言もしていただけるとありがたいです。
###該当のソースコード
c
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4 5int end_of_file = 0; 6 7struct word{ 8 9 char name[20]; 10 struct word *next; 11 int count; 12 13}; 14struct word *head; 15 16struct word* new(){ 17 18 struct word *p; 19 p = (struct word *)malloc(sizeof(struct word)); 20 p->next = NULL; 21 return p; 22 23} 24 25struct word *search(struct word *p, char *buffer){ 26 struct word *temp = p; 27 28 while(temp){ 29 if(strcmp(temp->name, buffer) == 0){ 30 return temp; 31 }else{ 32 temp = temp->next; 33 } 34 } 35 return NULL; 36} 37 38int read_word(FILE *file, char *buffer){ 39 40 char ch; 41 int n = 0; 42 buffer[0] = '\0'; 43 44 if(end_of_file == 1) 45 return 0; 46 47 while(1){ 48 ch = fgetc(file); 49 switch(ch){ 50 case ',': 51 case '.': 52 case '\n': 53 case ' ': 54 break; 55 case EOF: 56 end_of_file = 1; 57 break; 58 default: 59 buffer[n] = ch; 60 n++; 61 buffer[n] = '\0'; 62 continue; 63 } 64 if(buffer[0] == '\0') 65 return 1; 66 else 67 return n; 68 } 69} 70 71void delete(){ 72 struct word *temp, *del; 73 if(head != '\0'){ 74 temp = head; 75 while(temp){ 76 del = temp; 77 temp = temp->next; 78 free(del); 79 } 80 } 81 head = NULL; 82} 83 84int main(void){ 85 86 struct word *w, *b, *root; 87 char buf[20]; 88 int a = 0; 89 FILE *fp; 90 91 if((fp = fopen("anne.txt", "r")) == '\0'){ 92 printf("failed to open file\n"); 93 exit(1); 94 }else{ 95 w = new(); 96 head = w; 97 while(1){ 98 while(w->next != '\0') 99 w = w->next; 100 a = read_word(fp, buf); 101 b = search(head, buf); 102 if(a == 0) 103 break; 104 if(a == 1){ 105 if(w->name[0] != '\0'){ 106 if(b == NULL){ 107 strcpy(w->name, buf); 108 w->count++; 109 w->next = new(); 110 }else{ 111 w = b; 112 w->count++; 113 } 114 }else{ 115 continue; 116 } 117 }else{ 118 if(b == NULL){ 119 strcpy(w->name, buf); 120 w->count++; 121 w->next = new(); 122 }else{ 123 w = b; 124 w->count++; 125 } 126 } 127 } 128 root = head; 129 while(root->next != '\0'){ 130 printf("%s %d\n", root->name, root->count); 131 root = root->next; 132 } 133 fclose(fp); 134 } 135 delete(); 136 return 0; 137} 138
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/10 13:53
2017/07/10 14:57 編集
2017/07/10 20:29
2017/07/11 05:54