gpt4 book ai didi

c - 如何从c中的文件中读取多种数据类型

转载 作者:行者123 更新时间:2023-11-30 18:44:34 26 4
gpt4 key购买 nike

我必须读取一个包含杂货列表的文件,每行有 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

enter image description here

更新

感谢您的所有帮助,我已经使它可以使用此 while(fscanf(fp, "%[^,],%[^,],%f\n", Category, name, &price ) == 3),有人能解释一下它的作用吗?

最佳答案

解决办法是:

    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[100];
char name[100];
float price;

if(fp == NULL)
{
printf("Error in loading file.\n");
return 0;
}
else
{
while(fscanf(fp, "%[^,],%[^,],%f\n", category, name, &price) == 3))
{
Grocery *newN = addNew(category, name, price);

head = add_on_beginning(head, newN);
}
}

fclose(fp);

printf("File loaded successfully.\n");

return head;
}

关于c - 如何从c中的文件中读取多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57710301/

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