回答編集履歴

2

修正

2018/10/20 23:55

投稿

katoy
katoy

スコア22324

test CHANGED
@@ -74,7 +74,7 @@
74
74
 
75
75
  while (1) {
76
76
 
77
- char* s = fgets(line, N, fp);
77
+ char* s = fgets(line, N - 1, fp);
78
78
 
79
79
  if (s == NULL) {
80
80
 
@@ -98,7 +98,7 @@
98
98
 
99
99
  printf("Input a words: ");
100
100
 
101
- fgets(input, N, stdin);
101
+ fgets(input, N - 1, stdin);
102
102
 
103
103
  p = strchr(input, '\n');
104
104
 

1

追記

2018/10/20 23:55

投稿

katoy
katoy

スコア22324

test CHANGED
@@ -27,3 +27,107 @@
27
27
  > 全行を読み込んだ場合、又はエラー時にNULL(\0)を返す。
28
28
 
29
29
  > ...
30
+
31
+
32
+
33
+ 追記:
34
+
35
+ 変更例を示します。
36
+
37
+ (動作は質問文コードとは一致していませんが、ファイルからの読み込み、キーボードからの入力、改行コードの削除は動作しています)
38
+
39
+ ```c
40
+
41
+ #include<stdio.h>
42
+
43
+ #include<stdlib.h>
44
+
45
+ #include<string.h>
46
+
47
+
48
+
49
+ #define N (100)
50
+
51
+
52
+
53
+ int main() {
54
+
55
+ FILE *fp;
56
+
57
+ char line[N], input[N];
58
+
59
+ char *p;
60
+
61
+
62
+
63
+ if ((fp =fopen("words.txt", "r")) == NULL) {
64
+
65
+ printf("can not open words.txt\n");
66
+
67
+ exit(1);
68
+
69
+ }
70
+
71
+
72
+
73
+ // 文字列を比較する
74
+
75
+ while (1) {
76
+
77
+ char* s = fgets(line, N, fp);
78
+
79
+ if (s == NULL) {
80
+
81
+ break;
82
+
83
+ }
84
+
85
+
86
+
87
+ p = strchr(line, '\n');
88
+
89
+ if(p != NULL) {
90
+
91
+ *p = '\0';
92
+
93
+ }
94
+
95
+ printf("[%s]\n", line);
96
+
97
+
98
+
99
+ printf("Input a words: ");
100
+
101
+ fgets(input, N, stdin);
102
+
103
+ p = strchr(input, '\n');
104
+
105
+ if(p != NULL) {
106
+
107
+ *p = '\0';
108
+
109
+ }
110
+
111
+ // printf("[%s]\n", input);
112
+
113
+
114
+
115
+ if (strcmp(line, input) == 0) {
116
+
117
+ printf("'%s' == '%s'\n", line, input);
118
+
119
+ } else {
120
+
121
+ printf("'%s' != '%s'\n", line, input);
122
+
123
+ }
124
+
125
+ }
126
+
127
+ fclose(fp);
128
+
129
+ return 0;
130
+
131
+ }
132
+
133
+ ```