質問するログイン新規登録

質問編集履歴

2

コードの修正をしました。

2021/12/08 06:55

投稿

sawayakaunagi
sawayakaunagi

スコア17

title CHANGED
File without changes
body CHANGED
@@ -1,4 +1,4 @@
1
- ファイルを読み込み、文字数と行数をカウントするプログラムを作成したのですが、実行に数字が表示されませんが問題でしょうか?
1
+ ファイルを読み込み、文字数と行数をカウントするプログラムを作成したのですが、実行すると、out.txt表示されるのですが、文字数が0となっていしたなぜうなるのでしょうか?
2
2
  ```c
3
3
  コード
4
4
  #include<stdio.h>
@@ -17,27 +17,26 @@
17
17
  printf("Cannot open file¥n");
18
18
  return 1;
19
19
  }
20
- if( fgets(str, 2048, fp) != NULL )
20
+ while( fgets(str, 2048, fp) != NULL )
21
21
  {
22
22
  line ++;
23
23
  }
24
- if( fgetc(fp) != EOF )
24
+ while(( c = fgetc(fp)) != EOF )
25
25
  {
26
- word ++;
26
+ word ++;
27
27
  }
28
28
  fclose(fp);
29
29
 
30
- FILE *fp2;
30
+ fp = fopen("out.txt", "w");
31
31
 
32
- fp2 = fopen("out.txt", "w");
33
- if( fp2 == NULL)
32
+ if( fp == NULL)
34
33
  {
35
34
  printf("Cannot open file¥n");
36
35
  return 1;
37
36
  }
38
- printf("Number of lines ="); fprintf( fp, "%d", line);
37
+ fprintf( fp, "%d\n", line);
39
- printf("Number of words ="); fprintf( fp, "%d", word);
38
+ fprintf( fp, "%d", word);
40
- fclose( fp );
39
+ fclose( fp );
41
40
  return 0;
42
41
  }
43
42
  ```

1

list.txtの内容を追加しました。

2021/12/08 06:55

投稿

sawayakaunagi
sawayakaunagi

スコア17

title CHANGED
File without changes
body CHANGED
@@ -40,4 +40,36 @@
40
40
  fclose( fp );
41
41
  return 0;
42
42
  }
43
+ ```
44
+ ```c
45
+ list.txtの中身です。
46
+
47
+ List of countries and dependencies by population density
48
+ From Wikipedia, the free encyclopedia
49
+ This is a list of countries and dependent territories ranked by area and by population.
50
+ Area includes land and water.
51
+
52
+ Number of countries in the list: 7
53
+ Countries: Australia China India Japan Russia UK US
54
+
55
+ List of population
56
+ Countries Population
57
+ China 1400055440
58
+ India 1354969000
59
+ US 330263247
60
+ Russia 146877088
61
+ Japan 126577691
62
+ UK 66435600
63
+ Australia 25525452
64
+
65
+ List of area
66
+ Countries Area
67
+ Russia 17125242
68
+ US 9833517
69
+ China 9640821
70
+ Australia 7692024
71
+ India 3287240
72
+ Japan 377944
73
+ UK 242910
74
+
43
75
  ```