【发布时间】:2016-12-21 03:56:18
【问题描述】:
我的代码应该找到产品 ID、名称、数量和价格。 输入产品 ID 时,应打印产品 ID 所在的整行。
文本文件包含此输入:
1 CADBURY 999 1.900000
2 PEPSI 999 2.500000
3 IPHONE 976 2500.000000
4 SPIRULINA 100 50.000000
代码已使用输入“4”进行编译。但是输出是循环的:
Please enter product ID :
它没有读取“4”的整行。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
int addProduct();
struct product
{
int quantity, reorder, i, id;
char name[20];
float price;
};
int secondmain()
{
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);
}
/*-------------- ERROR START HERE-----------------*/
int main()
{
FILE * fp;
system("cls");
struct product a;
char array[255];
int productID;
fp = fopen("addproduct.txt","r");
while(1){
fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price);
productID = atoi(array);
printf("Please enter product ID : ");
scanf(" %d", &productID);
if(productID == a.id)
{
fgets(array, 255, (FILE*)fp);
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}
}
return(0);
}
【问题讨论】:
-
请显示Minimal, Complete, and Verifiable example,因为您没有显示标题或
struct product。否则我的第一个观察是productID = atoi(array);正在使用 未初始化的变量。 -
if(a.id = productID):使用==而不是= -
编译器警告不是为了好玩!启用它们并注意它们。在寻求帮助之前解决警告。
-
请按照习惯检查来自
fopen、scanf和fgets的函数返回值。 -
@WeatherVane 抱歉。已经编辑问题。是的,我想问一下 fgets 是否可以更改为其他内容。