gpt4 book ai didi

c - C语言读取文件出错

转载 作者:行者123 更新时间:2023-11-30 21:08:28 25 4
gpt4 key购买 nike

图 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;



}

另外我想知道,如果一个item的名称不超过50个字符,itemName数组中有多少个元素?

最佳答案

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

关于c - C语言读取文件出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com