【发布时间】:2019-01-02 23:35:20
【问题描述】:
所以有一个我正在使用 fscanf() 的文件。我在我的代码中设置了一个条件,当 (fscanf(...) == EOF 时,程序需要中断我正在使用的函数目前在. 问题是, 在文件中没有更多文本行的任何情况下, 这个条件都不会满足. EOF 总是-1, 而 fscanf(...) 每次有一行代码时返回 4 , 和 3 当它没有任何东西可以搜索时(而不是 -1)。如果我添加一行与其他代码类似的代码,我将简单地获得一个 fscanf() 返回 4 的实例,然后再一次,它会给我一个 3。
可能是什么问题?提前谢谢!
示例文本文件内容:
克里斯托·乔戈斯,140,VAS。奥尔加斯 112
马拉库马拉库斯,150,德拉斯。巴加斯 12
TSIKOU GIJRAN,140,JABS。德拉加斯 1
TSIKOU BIRBAN,140,JABS。德拉加斯 1
DELHDHMHTRIOU SPYROS,50,速度。巴加斯 62
FOX SIN,40,BAN。忍者 1
代码:
#include <stdio.h>
#define M 100
typedef struct {
char name[30];
int apousies;
} studentT;
void readInput (FILE* infile, studentT students[], int *pApousies, int *pStudents);
int main()
{
char inputfilename[30];
FILE* infile;
while (1) {
printf("Input file name :");
gets(inputfilename);
infile = fopen(inputfilename, "r");
if (infile != NULL) break;
printf("Cannot open input file %s. Try again.\n", inputfilename);
}
studentT students[M];
int numberOfStudents = 0, numberOfApousies = 0;
readInput(infile, students, &numberOfApousies, &numberOfStudents);
fclose(infile);
return 0;
}
void readInput (FILE* infile, studentT students[], int *pApousies, int *pStudents)
{
int nscan, apousies, studcount, apouscount, line;
char name[30], comments[68], termch;
line = 0;
while (1)
{
nscan = fscanf(infile, "%30[^,], %d, %68[^\n]%c", name, &apousies, comments, &termch);
/* printf("onoma: %s apousies: %d sxolia: %s terma: %c\n", name, apousies, comments, termch);
printf("%d\n", nscan);
printf("%d\n", EOF);*/
if (nscan == EOF) break;
line++;
if (nscan != 4 || termch != '\n')
{
printf("Error in line %d. Program termination\n", line);
exit(1);
}
}
}
【问题讨论】:
-
(fscanf(...) == EOF程序需要突破的功能 --> 那是弱测试。最好针对一个期望的回报进行测试——也许像(fscanf(...) != 4。请发帖minimal reproducible example。 -
发布
studentT的定义。这篇文章更好,但还不够完整,无法编译。 -
我不确定代码的哪些部分与问题相关。我希望这有帮助。再次感谢。
-
请提供minimal reproducible example,准确显示您如何使用
fscanf(),尤其是您的实际格式字符串 -
请注意,您的代码很奇怪。您将
pApousies作为参数传递给函数readInput,但不要使用它。您声明一个局部变量apousies并在调用fscanf 时使用它。你对nscan == EOF的测试在我看来没问题。