我被要求制作一个 C 程序,作为“价格查询”,用户输入产品名称,程序将打印它的名称和价格,并将其存储在一个文件中。如果该项目不存在于文件中,程序将通知用户。只要用户想要搜索,程序就会一直循环。我使用 Dev C++ 进行了编码,但是在我运行代码后,程序在几次循环后卡住了,而且是随机的。你们能检测到我的编码有什么问题吗,还是只是 Dev C++ 的问题?我在下面包含我的代码。非常感谢您的帮助。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
int main()
{
FILE *items;
char *mode="r";
char pName[50];
float pPrice;
char p1Name[50];
int value=0;
char respond='Y';
char s[50];
items=fopen("Product_Name_Price.txt", mode);
if(items==NULL)
{
fprintf(stderr, "Can't open file Product_Name_Price.txt!\n");
exit(1);
}
printf("File has been successfully opened\n");
do
{
printf("Enter the name of the product you wish to look for\n");
scanf("%s", &p1Name);
while(strcmp(p1Name, pName) !=0)
{
fscanf(items,"%s %f", pName, &pPrice);
//printf("%s\t%.2f\n", pName, pPrice);
//value=strcmp(p1Name, pName);
if(strcmp(p1Name, pName) == 0)
{
printf("%s\t%.2f\n", pName, pPrice);
}
}
/*
else
{
printf("No data in system\n");
}
*/
printf("Do you wish to look up for more item? (Y/N)\n");
scanf("%s", &respond);
}while(respond=='Y'|| respond=='y');
printf("This program is closing\n");
fclose(items);
}
最佳答案
你的程序有未定义的行为,因为你的 scanf("%s", &response)
读入 response
就好像它是一个大小足以容纳正在读取的字符串的数组— 该大小至少 2(包括空终止符),但response
只是一个 字符。你炸毁了你的堆栈和损坏的内存,然后所有的赌注都被取消了。
您可以编写 scanf("%c", &response)
而不是实际读取单个字符,但如果您正在编写 C++,则最好切换到更现代、更安全的工具程序。
关于C - 价格查询程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814731/