gpt4 book ai didi

c - 从文件中读取整数

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:48 24 4
gpt4 key购买 nike

使用 feof() 函数,在我的输出文件中,我将最后一个值打印了两次。我怎样才能避免这种情况?我的输出应该是

1261513

and i have

126151313

Thank you!

while(!feof(pfile1))
{
sum=0;
fscanf(pfile1,"%d%d%d",&choice,&day,&val);
if(choice==0)
{
i=day-1;
a[i]=a[i]-val;
}
else if(choice==1)
{
for(i=day-1;i<=val-1;i++)
{
sum=sum+a[i];

}
fprintf(pfile2,"%d\n",sum);
}
}

最佳答案

一个选项是检查 fscanf 的返回值:

On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned.

所以,像这样:

if( fscanf(pfile1,"%d%d%d",&choice,&day,&val) <= 0 )
{
break;
}

另一个选项是在执行fscanf 之后检查feof。例如:

if( feof( pfile1 ) )
{
return; // or something
}
do
{
// the same loop body
}
while( ! feof( pfile1 ) );

关于c - 从文件中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com