#include <stdio.h>
int main()
{
int c=0,d=0;
FILE *f1;
f1 = fopen("F:\\num.txt" , "r");
while((c=getw(f1)) != EOF)
{
d+=c;
printf("\n%d",c);
}
fclose(f1);
printf("\n%d",d);
return 0;
}
我是 C 文件的初学者。我试图从名为“num.txt”的文件中找到数字的总和。文件中的内容是:
12486
所以输出应该是:21
但是当我运行代码时,我没有得到输出,而是得到如下内容:
540155953
那么这个错误在哪里呢?
最佳答案
while((c = fgetc(f1)) != EOF)
{
num = c - '0';
d+= num;
}
获取一个字符并将其转换为整数,然后执行加法。
关于c - 从文件中添加数字的示例 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606640/