回答編集履歴

2

別解

2020/10/15 05:31

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -41,3 +41,67 @@
41
41
  p_key や p_word を使用せず、key や word と書けばいいでしょう。
42
42
 
43
43
  buf も不要です。text で十分です。
44
+
45
+
46
+
47
+ **追記**
48
+
49
+ 解決済みなったので別解です。
50
+
51
+ ```C
52
+
53
+ #include <stdio.h> // printf, fgets, fopen, fclose, fscanf, perror
54
+
55
+ #include <string.h> // strchr, strcasecmp
56
+
57
+
58
+
59
+ int main(void)
60
+
61
+ {
62
+
63
+ int cnt = 0, all = 0, *p;
64
+
65
+ char key[100], word[100];
66
+
67
+
68
+
69
+ FILE *fp = fopen("test.txt","r");
70
+
71
+ if (fp == NULL) { perror("test.txt"); return 1; }
72
+
73
+
74
+
75
+ printf("Input a word for search and count: ");
76
+
77
+ if (!fgets(key, sizeof key, stdin)) return 2;
78
+
79
+ if (p = strchr(key, '\n')) *p = '\0';
80
+
81
+ printf("Input key = %s\n", key);
82
+
83
+
84
+
85
+ while (1) {
86
+
87
+ fscanf(fp, "%*[^a-zA-Z0-9]"); // 英数字以外を読み飛ばす
88
+
89
+ if (fscanf(fp, "%99[a-zA-Z0-9]", word) != 1) break; // 単語を取得
90
+
91
+ all++;
92
+
93
+ if (!strcasecmp(key, word)) cnt++;
94
+
95
+ }
96
+
97
+ fclose(fp);
98
+
99
+
100
+
101
+ printf("全単語数:%d\n", all);
102
+
103
+ printf("単語数:%d\n", cnt);
104
+
105
+ }
106
+
107
+ ```

1

単語数増加の説明の追加

2020/10/15 05:31

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -28,8 +28,16 @@
28
28
 
29
29
 
30
30
 
31
+ 単語数が実際より増えるのは、行頭にスペースがあったり、単語間のスペースが
32
+
33
+ 2個以上ある場合です。もう少しよく考えてみてください。
34
+
35
+
36
+
31
37
  ポインタ p_key や p_word は、配列 key や word の先頭を指している
32
38
 
33
39
  だけで一度も変更していません。
34
40
 
35
41
  p_key や p_word を使用せず、key や word と書けばいいでしょう。
42
+
43
+ buf も不要です。text で十分です。