这是我的代码。我不断收到错误。我认为发生错误的部分是读取int score[3]的部分。我该如何解决这个问题?
// code
typedef struct {
int no;
char name[TSIZE];
int score[3];
int sum;
double avg;
} Score;
int num;
if (fscanf(file, "%d%*c", &num) != 1){
printf("$ !ERROR: Wrong file format to num.\n");
exit(1);
}
*ptr_s_list = (Score *)malloc(sizeof(Score) * num);
if (*ptr_s_list == NULL){
printf("$ !ERROR: Malloc failed.\n");
exit(1);
}
for (int s = 0; s < num; ++s){
if (fscanf(file, "%d%*c", &(*ptr_s_list)[*ptr_s_items].no) != 1
|| fscanf(file, "%[^\n]%*c", (*ptr_s_list)[*ptr_s_items].name) != 1
|| fscanf(file, "%d %d %d", &(*ptr_s_list)[*ptr_s_items].score[0], &(*ptr_s_list)[*ptr_s_items].score[1], &(*ptr_s_list)[*ptr_s_items].score[2]) != 1
|| fscanf(file, "%d%*c", &(*ptr_s_list)[*ptr_s_items].sum) != 1
|| fscanf(file, "%lf%*c", &(*ptr_s_list)[*ptr_s_items].avg) != 1
){
printf("$ !ERROR: Wrong file format to \'%s\'.\n", filename);
exit(1);
}
(*ptr_s_items)++;
}
// txt
3 // this int num
1 jay 100 90 80 270 90.0
2 key 90 80 65 235 78.3
3 ray 90 45 65 200 66.7
告诉我如何解决它。
这里是一个解析输入文件的示例实现(删除了 // 内容)。
TSIZE+1
在读取字符串时使用最大字段宽度。main()
.size_t
而不是 int
来避免输入,比如说,-1。直到需要检查它是否为非零,因为 malloc(0)
的行为是实现定义的。fscanf()
阅读每一行。有7个字段,@Fe2O3已经指出读取3个字段时1的错误返回值检查。读取 name
字符串时使用最大字段宽度。fgets()
阅读一行并用 sscanf()
处理它。这使您可以访问正在解析的整个字符串,进而可以生成更好的错误消息。#include <stdio.h>
#include <stdlib.h>
#define TSIZE 42
#define str(s) str2(s)
#define str2(s) #s
typedef struct {
int no;
char name[TSIZE+1];
int score[3];
int sum;
double avg;
} Score;
int main() {
// declarations with well-defined values needed before first goto
FILE *f;
Score *ptr_s_list = NULL;
f = fopen("sample.txt", "r");
if(!f) {
printf("could not open filed\n");
goto out;
}
size_t num;
if(fscanf(f, "%zu", &num) != 1 || !num) {
printf("$ !ERROR: Wrong file format to num.\n");
goto out;
}
ptr_s_list = malloc(sizeof *ptr_s_list * num);
if(!ptr_s_list) {
printf("malloc failed\n");
goto out;
}
for(Score *p = ptr_s_list; p < ptr_s_list + num; p++) {
int rv = fscanf(f, "%d%" str(TSIZE) "s%d%d%d%d%lf",
&p->no,
p->name,
&p->score[0],
&p->score[1],
&p->score[2],
&p->sum,
&p->avg
);
if(rv != 7) {
printf("$ !ERROR: Wrong file format; %d of 7 fields read\n", rv);
goto out;
}
// printf("%d %s %d %d %d %d %g\n", p->no, p->name, p->score[0], p->score[1], p->score[2], p->sum, p->av g);
}
out:
free(ptr_s_list);
if(f) fclose(f);
}