【发布时间】:2020-01-02 17:42:23
【问题描述】:
我必须读取一个包含杂货列表的文件,每行包含 3 个部分:类别、名称、价格
这就是文件的样子:
Fruit,Apple,15.6
Vegetable,Potato,20.0
Fruit,Banana,17.0
Vegetable,Lettuce,13.5
我无法读取这些值并将它们放入链接列表中。
我相信我唯一的问题是正确阅读它们并将它们加载到链接列表中。我用 fscanf 尝试了许多不同的组合,但似乎都没有。
typedef struct Grocery Grocery;
struct Grocery
{
char category[100];
char name[100];
float price;
Grocery *next;
};
Grocery *addNew(char *category, char *name, float price)
{
Grocery *newN = (Grocery*)malloc(sizeof(Grocery));
strcpy(newN->category, category);
strcpy(newN->name, name);
newN->price = price;
newN->next = NULL;
return newN;
}
Grocery *add_on_beginning(Grocery *head, Grocery *newN)
{
newN->next = head;
return newN;
}
Grocery *load_file(Grocery *head)
{
char filename[100];
scanf("%s", filename);
FILE *fp = fopen(filename, "r");
char *category;
char *name;
float price;
if(fp == NULL)
{
printf("Error in loading file.\n");
return 0;
}
else
{
while(!feof(fp))
{
fscanf(fp, "%s,%s,%lf\n", category, name, &price);
Grocery *newN = addNew(category, name, price);
head = add_on_beginning(head, newN);
}
}
fclose(fp);
printf("File loaded successfully.\n");
return head;
}
每当我调试代码时,在打印每个元素后都会得到随机数字和字母,我会得到:
ï&╪5Ç@ 0.000000
更新
感谢大家的帮助,我已经用这个while(fscanf(fp, "%[^,],%[^,],%f\n", category, name, &price) == 3) 让它工作了,有人能解释一下它的作用吗?
【问题讨论】:
-
error in loading file是不是有用的错误消息。使用perror(filename) -
变量
char *category; char *name;没有分配任何内存。另请参阅Why iswhile ( !feof (file) )always wrong? 您应该使用fscanf的结果驱动循环,例如while(fscanf(...) == 3) { ... }。此外,%lf是fscanf中float的错误格式说明符,它应该是%f。 -
我已经更改了代码,对于 while 条件,我把这个 while(fscanf(fp, "%s,%s,%f\n", category, name, &price) == 3 ),我也把char *category改成了char category[100],和name一样,现在调试程序时,列表连打印都打印不出来了。
-
您没有检查
fscanf或scanf的返回值。这将是一个开始。 -
...因此程序无法为您提供的输入生成您显示的结果,因为它在每一行中都没有空格。
标签: c file linked-list