读取文件C编程时出错

读取文件C编程时出错,c,C,图1显示了一个文本文件(itemlist.txt),它存储项目代码、项目名称、项目价格和项目数量。编写一个程序,从文本文件中读取数据,然后在屏幕上显示数量为0的项目信息 假设文件中存储的数据为: itemCode a unique unsigned integer that differentiates an item from another itemName the name of an item (not more than 50 charact

图1显示了一个文本文件(itemlist.txt),它存储项目代码、项目名称、项目价格和项目数量。编写一个程序,从文本文件中读取数据,然后在屏幕上显示数量为0的项目信息

假设文件中存储的数据为:

itemCode            a unique unsigned integer that differentiates an item from another
itemName            the name of an item (not more than 50 characters)
itemPrice           the current selling price of an item
itemQuantity        an integer that shows the quantity of an item               
另外,假设文件中的字段用逗号分隔

文件内容:

 3123,Potato Chips,3.99,8
 2213,Peanut butter,7.99,0
 4533,Candy,1.05,14
 8744,Ice cream,2.50,0
示例输出:

 Out-of-stock items:
 -------------------------------
 2213   Peanut butter   7.99
 8744   Ice cream   2.50
有人能读懂我的代码,看看有什么问题吗?程序异常退出,但我不知道为什么

#include <stdio.h>
#include <stdlib.h>
 int main()
 {
   unsigned int itemCode;
   char itemName[50];
   float itemPrice;
   int itemQuantity;

   FILE *fp;
   fp = fopen("itemlist.txt", "r");
   printf("%s","Out-of-stock items: \n");
   printf("-------------------------");

   while(!feof(fp)) {
    fscanf(fp, "%4u,%[^,],%f,%d", &itemCode, itemName, &itemPrice, &itemQuantity);

    if(itemQuantity == 0){
        printf("%u %s %f\n",itemCode,itemName,itemPrice);
    }


   }
    fclose(fp);

    return 0;



}
#包括
#包括
int main()
{
无符号整数项码;
char itemName[50];
浮动价格;
整数项数量;
文件*fp;
fp=fopen(“itemlist.txt”,“r”);
printf(“%s”,“缺货项目:\n”);
printf(“---------------------------”);
而(!feof(fp)){
fscanf(fp、%4u、%[^、]、%f、%d”、&itemCode、itemName、&itemPrice和&itemQuantity);
如果(itemQuantity==0){
printf(“%u%s%f\n”、项目代码、项目名称、项目价格);
}
}
fclose(fp);
返回0;
}

我还想知道,如果一个项目的名称不超过50个字符,那么项目名称数组中有多少个元素?

您的主要问题可能不是您的程序,而是您的环境。我已经测试了你的程序,它没有崩溃,它确实为有问题的文件提供了正确的输出。您应该检查您的文件权限或使用该程序创建一个新项目,然后它就可以工作了

如果某些输入记录包含
itemName
50个或更多字符长度,则代码会导致未定义的行为,因为您使用的缓冲区有限:

char itemName[50];

也许最好实现自定义解析,因为
scanf()
不够灵活,无法满足所有可能的输入。

这里的图1是什么请提供图表或删除该部分?也许检查
fscanf
的返回值是一个很好的起点,但其他问题除外(检查
fscanf
返回值并读取上面的我的链接)仍然存在