我有具有以下内容的文本文件:
T(10,0.75) T(5,0.75)
P(5,0.55)
和类似的代码来阅读它:
FILE* file = fopen("abc.txt", "r");
char a;
int b;
float c;
int returnCode;
do {
returnCode = fscanf(file, "%c(%d,%f)", &a, &b, &c);
printf("%c(%d,%f)\n", a, b, c);
} while (returnCode > 0);
fclose(file);
我期望do..while循环将迭代两次,然后我必须手动读取\n
char。否则它会迭代三遍,而忽略换行符。但是,我得到以下输出:
T(10,0.750000)
(10,0.750000)
T(5,0.750000)
(5,0.750000)
P(5,0.550000)
(5,0.550000)
(5,0.550000)
fscanf
似乎再次从文件中重用文本,而不是跳过它并阅读下一部分。
如何正确使用它,所以我将得到这样的printf输出:
T(10,0.750000)
T(5,0.750000)
即使在循环的最后一次迭代中,即使a
为0,您仍然会打印b
,c
和returnCode
的值。您需要在打印前检查一下。
do {
returnCode = fscanf(file, "%c(%d,%f)", &a, &b, &c);
if (returnCode > 0) printf("%c(%d,%f)\n", a, b, c);
} while (returnCode > 0);