回答編集履歴

1

追記

2017/12/11 23:44

投稿

LouiS0616
LouiS0616

スコア35658

test CHANGED
@@ -1 +1,115 @@
1
1
  `/n`じゃなくて`\n`では?
2
+
3
+
4
+
5
+ 追記
6
+
7
+ ---
8
+
9
+ こちらのコードで動作確認できました。[Wandbox](https://wandbox.org/permlink/6ojKA8M1LE6DS4Au)
10
+
11
+ 追加した関数は表記を簡単にする目的しかありませんので、適宜読み捨ててください。
12
+
13
+ ```C
14
+
15
+ #include <stdio.h>
16
+
17
+ #include <stdlib.h>
18
+
19
+
20
+
21
+ typedef struct {
22
+
23
+ int code;
24
+
25
+ char name[100];
26
+
27
+ int math;
28
+
29
+ int eng;
30
+
31
+ } Student;
32
+
33
+
34
+
35
+ int fscan_student(FILE *fp, Student *dst) {
36
+
37
+ return fscanf(
38
+
39
+ fp, "%d%s%d%d\n",
40
+
41
+ &dst->code, dst->name, &dst->math, &dst->eng
42
+
43
+ );
44
+
45
+ }
46
+
47
+ int fprint_student(FILE *fp, const Student *src) {
48
+
49
+ return fprintf(
50
+
51
+ fp, "番号%d番%sの数学は%d点で,英語は%d点.\n",
52
+
53
+ src->code, src->name, src->math, src->eng
54
+
55
+ );
56
+
57
+ }
58
+
59
+
60
+
61
+ int main(void) {
62
+
63
+ FILE *fp = fopen("test.txt", "r");
64
+
65
+ if(fp == NULL) {
66
+
67
+ return EXIT_FAILURE;
68
+
69
+ }
70
+
71
+
72
+
73
+ Student students[20];
74
+
75
+
76
+
77
+ while(fgetc(fp) != '\n');
78
+
79
+ for(int i = 0; fscan_student(fp, &students[i]) != EOF; ++i) {
80
+
81
+ fprint_student(stdout, &students[i]);
82
+
83
+ }
84
+
85
+
86
+
87
+ fclose(fp);
88
+
89
+ return EXIT_SUCCESS;
90
+
91
+ }
92
+
93
+ ```
94
+
95
+
96
+
97
+ cateyeさんがご指摘されている点に加えて、fgetcの戻り値の扱いに誤りがありました。
98
+
99
+ > ```C
100
+
101
+ while (fgetc(fp) != "/n") ;
102
+
103
+ > ```
104
+
105
+
106
+
107
+ このままでは、fgetcの戻り値と比較しているのは文字列のアドレスです。
108
+
109
+ 文字自体と比較するためには、シングルクオーテーションで括る必要があります。
110
+
111
+ ```C
112
+
113
+ while(fgetc(fp) != '\n');
114
+
115
+ ```