我做了一个程序来计算input.txt中的数字:
输入.txt
13 1 17 3 14 10 18 18 16 13 15 5 5 6 12 8 8 3 2 5 4 10 11 3 1 5 10 1 7 5 6 10 9 4 3 10 15 13
主程序
#include<stdio.h>
int main()
{
FILE *fptr;
fptr=fopen("input.txt","r");
int data;
int count=0;
while(!feof(fptr))
{
fscanf(fptr,"%d",&data);
count++;
}
printf("%d",count);
}
结果是无限字符 'p' ???
最佳答案
这个有效:
#include <stdio.h>
int main(void) {
FILE *fptr;
if (!(fptr = fopen("input.txt", "r"))) {
printf("Could not open file\n");
return 1;
}
int data, count;
for (count = 0; fscanf(fptr, "%d ", &data) == 1; count++)
;
printf("%d\n", count);
fclose(fptr);
return 0;
}
请注意我对您的代码所做的以下调整。
您没有进行任何错误检查以查看“input.txt”是否存在。你不应该编写假设这样的代码,即使是小程序。如果输入文件不存在,此程序现在会打印一条错误消息并向 shell 返回 1。
while (!feof(fptr))
是不好的做法,而且通常不起作用。要检查文件中是否有剩余数据,请使用scanf()
语句本身作为循环条件。为了方便和高效,我将其设为 for 循环。您没有对文件指针执行
fclose()
。这是绝对必要的,因为您不希望文件指针在内存中 float ,并且您希望您的系统/shell 知道该文件不再被使用。int main()
成功时应始终返回 0。
如果你这样做,我想不出你的编译器或二进制文件为什么会像那样打印“pppppp”。如果它继续这样做,则说明您的编译器或工作空间有问题。
关于c - 在 C 中使用 fscanf 时输出无限字符 'p',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949530/