C如果有其他选择

C如果有其他选择,c,selection,C,Selection,我试图找出如何计算出当文本文件中没有输入信息时的选择,用户将收到通知。现在,当我运行代码并输入一个不在文本文件中的项目时,它只打印出文本文件中的最后一个项目。在思考了几个小时如何解决这个问题后,我真的被困住了。非常感谢你的帮助 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<conio.h> #include<ctype.h> int main() {

我试图找出如何计算出当文本文件中没有输入信息时的选择,用户将收到通知。现在,当我运行代码并输入一个不在文本文件中的项目时,它只打印出文本文件中的最后一个项目。在思考了几个小时如何解决这个问题后,我真的被困住了。非常感谢你的帮助

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>

int main()
{
    FILE *items;

    char pName[20];
    float pPrice;
    char p1Name[20];
    int found=0, i=9;
    char respond='y';

    items=fopen("Product_Name_Price.txt", "r");

    if(items==NULL)
    {
        fprintf(stderr, "Can't open file Product_Name_Price.txt!\n");
        exit(1);
    }

    printf("File has been successfully opened\n");

    while(tolower(respond) == 'y')
    {
        items=fopen("Product_Name_Price.txt", "r");
        printf("Enter the name of the product you are looking for\n");
        scanf("%s", p1Name);

        while(!feof(items))
        {
            fscanf(items, "%s%f", pName, &pPrice);
            i=strcmp(p1Name, pName);

            if(i == 0)
            {
                found=1;
                break;
            }
            else
            {
                found=0;
            }
        }
        if(found=1)
        {
            printf("%s\t%.2f\n", pName, pPrice);
        }
        else
        {
            printf("No such product information in the database\n");
        }

        printf("Do you want to look for more item? (Y/N)\n");
        scanf(" %c", &respond);
        fclose(items);
    }
}
#包括
#包括
#包括
#包括
#包括
int main()
{
档案*项目;
char-pName[20];
浮冰;
字符名称[20];
int=0,i=9;
char='y';
items=fopen(“Product_Name_Price.txt”、“r”);
if(items==NULL)
{
fprintf(stderr,“无法打开文件Product\u Name\u Price.txt!\n”);
出口(1);
}
printf(“文件已成功打开\n”);
while(tolower(response)='y')
{
items=fopen(“Product_Name_Price.txt”、“r”);
printf(“输入您要查找的产品的名称\n”);
scanf(“%s”,p1Name);
而(!feof(项目))
{
fscanf(项目“%s%f”、pName和pPrice);
i=strcmp(p1Name,pName);
如果(i==0)
{
发现=1;
打破
}
其他的
{
发现=0;
}
}
如果(发现=1)
{
printf(“%s\t%.2f\n”,pName,pPrice);
}
其他的
{
printf(“数据库中没有此类产品信息”);
}
printf(“是否要查找更多项目?(Y/N)\N”);
scanf(“%c”,&respond);
fclose(项目);
}
}

如果(发现=1)
应该是
如果(发现=1)
而(!feof(…
是。为什么会这样?对不起,我对编程很陌生。@PaulRSee,请提供完整的解释和如何正确操作。这个问题是由一个无法再复制的问题或一个简单的印刷错误引起的。虽然这里可能有类似的问题,但这个问题的解决方式不太可能对未来的读者有所帮助。这个c在发布之前,通过识别并仔细检查重现问题所需的最短程序,通常可以避免问题。哇,这是一个愚蠢的错误。非常感谢@MukulGupta btw你知道我如何使用tolower()吗函数以避免在比较字符串时出现与大小写相关的问题?我认为C标准中没有对字符数组进行不区分大小写的字符串比较。在对字符串调用strcmp之前,可以对这两个字符串进行迭代并将其转换为小写。@SafiuddinMansor在编译时使用
-Wall
,并且会出现关于t的警告他的。@SafiuddinMansor同样,保持以相反的方式编写这些表达式的习惯,即如果(1=found)
将给出一个编译器错误。