【发布时间】:2015-03-16 19:52:41
【问题描述】:
当我输入我想要的内容时文件没有显示,但它也没有给我错误。
文件是:
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
int main(void)
{
int account;
char name[30];
float balance;
int request;
char singleline[150];
FILE * fpointer;
fpointer = fopen("acc.txt","r");
while (!feof(fpointer))
{
fgets(singleline, 150, fpointer);
}
if ((fpointer= fopen("acc.txt", "r"))==NULL)
printf("File could not be opened\n");
else
{
printf("Enter Request\n"
"1 - List accounts with zero balances\n"
"2 - List accounts with credit balances\n"
"3 - List accounts with debit balances\n"
"4 - Endof run\n");
scanf("%d", &request);
while (request !=4)
{
fscanf(fpointer,"%d%s%f", &account,name, &balance);
switch(request)
{
case 1:
printf("\nAccounts with zero balnces:\n");
while(!feof(fpointer))
{
if (balance ==0)
printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(fpointer,"%d%s%f", &account,name, &balance);
}
break;
case 2:
printf("\nAccounts with credit balances:\n");
while(!feof(fpointer))
{
if (balance<0)
printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(fpointer,"%d%s%f", &account,name, &balance);
}
break;
case 3:
printf("\nAccounts with debit balances:\n");
while(!feof(fpointer))
{
if (balance>0)
printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(fpointer,"%d%s%f", &account,name, &balance);
}
break;
}
rewind (fpointer);
printf("\n?" );
scanf("%d",&request);
}
printf("End of run.\n");
}
fclose(fpointer);
system("pause >nul");
return 0;
}
【问题讨论】:
-
while (!feof(fpointer))is always wrong. 如果你不检查,你怎么知道文件没有打开? -
你可以使用函数吗?问题:第一个
while循环是做什么用的?它应该是while (fgets(singleline, sizeof(singleline), fpointer)) {} -
@iharob +1 有很多关于不正确使用
feof()的问题 -
没有明确说明您要做什么,或者问题是什么。 “文件不显示” 是什么意思?你甚至没有检查
fopen()的结果。 -
我看到您正在使用
float和if (balance == 0),当balance是根据无法在float中精确表示的值计算时容易出现不等式。查看最近的问题stackoverflow.com/questions/29084695/…