以下是TEXT FILE的输入:
19 BISON-BURGER 10 15.000000
10 BRAISED-COD 5 17.000000
23 MOJITO 8 11.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000
输入密钥后输出来自编译器:
10 BRAISED-COD 5 17.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000
为什么编译器会跳过某些行?我需要做出哪些改变?
请帮忙。非常感谢。
以下是完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
struct product
{
int quantity, reorder, i, id;
char name[20];
float price;
};
int main()
{
FILE * fp;
int i=0;
struct product a;
system("cls");
char checker;
do
{
fp = fopen("addproduct.txt","a+t");
system("cls");
printf("Enter product ID : ");
scanf(" %d", &a.id);
printf("Enter product name : ");
scanf(" %s", a.name);
printf("Enter product quantity : ");
scanf(" %d", &a.quantity);
printf("Enter product price : ");
scanf(" %f", &a.price);
fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
printf("Record saved!\n\n");
fclose(fp);
printf("Do you want to enter new product? Y / N : ");
scanf(" %c", &checker);
checker = toupper(checker);
i++;
system("cls");
}
while(checker=='Y');
if(checker == 'N')
{
fp = fopen("addproduct.txt","r");
while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price);
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}
fclose(fp);
}
return(0);
}
答案 0 :(得分:1)
在输出循环的每次迭代中,您正在从文件中读取两行。摆脱额外的scanf
:
while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}
答案 1 :(得分:0)
您每次通过fscanf()
循环调用while
两次。首先是while
条件,然后是循环体。您只打印第二个读取的变量,因此忽略第一个fscanf()
读取的行。摆脱第二个fscanf()
。
while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}