C - 价格查询程序

标签 c loops

我被要求制作一个 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/

相关文章:

c - 在 C 中排序链表的问题

c - 嵌入式 C 将字符串传递给函数

c - C中的RTSP服务器没有客户端响应

Python -TypeError : 'int' object is not iterable

python - 如何遍历嵌套列表以从 1 到 5 对每个列表进行编号 :

c - 为什么我的程序不能使用 float 变量,但可以使用 int 变量?

c++ - 处理内存分配时的保护标志

ruby - 在 ruby​​ 中创建两个日期之间的月份范围

javascript - for循环的语法有多严格

r - 在 r 中应用函数太慢