回答編集履歴

1

先頭が同じ単語があった時の不具合を修正

2022/06/19 18:35

投稿

tatsu99
tatsu99

スコア5458

test CHANGED
@@ -1,18 +1,16 @@
1
1
  以下のようにしてください。
2
2
  ```C
3
3
  #include <stdio.h>
4
- #include<stdlib.h>
4
+ #include <stdlib.h>
5
- #include<string.h>
5
+ #include <string.h>
6
-
7
-
8
6
  int main()
9
7
  {
10
-
11
8
  char data[256];
12
9
  FILE *fp;
13
10
  char buf[256];
14
- int i;
15
- char *p;
11
+ char *p; //fgets 判定用
12
+ char *p1; //最初に出現した空白の位置
13
+ char *p2; //最後に出現した空白の位置
16
14
  int flg = 0;
17
15
  scanf("%s", &buf);
18
16
 
@@ -23,11 +21,13 @@
23
21
  while(1){
24
22
  p = fgets(data, sizeof(data), fp);
25
23
  if (p == NULL) break;
26
- if (strncmp(buf, &data[i], strlen(buf)) == 0) {
24
+ p1 = strchr(data,' ');
25
+ if (p1 == NULL) continue;
27
- p = strrchr(data,' ');
26
+ p2 = strrchr(data,' ');
28
- if (p == NULL) continue;
27
+ *p1 = '\0';
29
- p++;
28
+ p2++;
29
+ if (strcmp(buf,data) == 0) {
30
- fputs(p, stdout);
30
+ fputs(p2,stdout);
31
31
  flg = 1;
32
32
  break;
33
33
  }