在同一 .c 文件中写入和读取时,fscanf 不会读取文本文件中的所有值
fscanf doesn't read all values in a text file when written and read in same .c file
有一道题,我需要在一个文本文件中写入10001个int值,然后在同一个程序中,读取这些值并存储在一个int值中,以求出总和。但是当我在同一个程序(同一个 .c 文件?)中执行这两个操作时,它不会读取最后 200 个值,因此总数比预期的要少。如果您知道是什么原因造成的,请写信,我们将不胜感激 :) 提前致谢!
Ps: 我是编码初学者,尤其是C编程,如果我的代码有严重错误请原谅我...
#include <stdio.h>
int main ()
{
//a)
FILE * fp = fopen ("deneme.txt","w");
int I;
for(i=0;i<=10001;i++) {
if(i%10==0){
fprintf(fp,"\n");
}
fprintf(fp,"%5d ",i);
}
´ /* when i write and read in different .c
files, it shows the correct answer which is:
Total sum: 50015001
from how many values: 10002
but instead it gives me this:
Total sum: 48083730
from how many values: 9808
*/´
//b)
FILE* file = fopen ("deneme.txt", "r");
int j,counter =0;
int sum = 0;
while ((fscanf (file, "%d", &j)) != EOF)
{
counter++;
sum+=j;
}
fprintf(stdout,"Total sum: %d\n",sum);
printf("from how many values: %d",counter);
fclose (file);
return 0;
}
这个有效
#include <stdio.h>
int main ()
{
//a)
FILE * fp = fopen ("deneme.txt","w");
int i;//YOU HAD A TYPO HERE
for(i=0;i<=10001;i++) {
if(i%10==0){
fprintf(fp,"\n");
}
fprintf(fp,"%5d ",i);
}
fclose(fp); //ADD THIS
//b)
FILE* file = fopen ("deneme.txt", "r");
int j,counter =0;
int sum = 0;
while ((fscanf (file, "%d", &j)) != EOF)
{
counter++;
sum+=j;
}
fprintf(stdout,"Total sum: %d\n",sum);
printf("from how many values: %d",counter);
fclose (file);
return 0;
}
有一道题,我需要在一个文本文件中写入10001个int值,然后在同一个程序中,读取这些值并存储在一个int值中,以求出总和。但是当我在同一个程序(同一个 .c 文件?)中执行这两个操作时,它不会读取最后 200 个值,因此总数比预期的要少。如果您知道是什么原因造成的,请写信,我们将不胜感激 :) 提前致谢!
Ps: 我是编码初学者,尤其是C编程,如果我的代码有严重错误请原谅我...
#include <stdio.h>
int main ()
{
//a)
FILE * fp = fopen ("deneme.txt","w");
int I;
for(i=0;i<=10001;i++) {
if(i%10==0){
fprintf(fp,"\n");
}
fprintf(fp,"%5d ",i);
}
´ /* when i write and read in different .c
files, it shows the correct answer which is:
Total sum: 50015001
from how many values: 10002
but instead it gives me this:
Total sum: 48083730
from how many values: 9808
*/´
//b)
FILE* file = fopen ("deneme.txt", "r");
int j,counter =0;
int sum = 0;
while ((fscanf (file, "%d", &j)) != EOF)
{
counter++;
sum+=j;
}
fprintf(stdout,"Total sum: %d\n",sum);
printf("from how many values: %d",counter);
fclose (file);
return 0;
}
这个有效
#include <stdio.h>
int main ()
{
//a)
FILE * fp = fopen ("deneme.txt","w");
int i;//YOU HAD A TYPO HERE
for(i=0;i<=10001;i++) {
if(i%10==0){
fprintf(fp,"\n");
}
fprintf(fp,"%5d ",i);
}
fclose(fp); //ADD THIS
//b)
FILE* file = fopen ("deneme.txt", "r");
int j,counter =0;
int sum = 0;
while ((fscanf (file, "%d", &j)) != EOF)
{
counter++;
sum+=j;
}
fprintf(stdout,"Total sum: %d\n",sum);
printf("from how many values: %d",counter);
fclose (file);
return 0;
}