我没有看到类似的东西,所以我决定问问自己。我正在尝试为我的一个类编写一个程序,您可以从文件中读取一组有关杂货的数据,并将其存储在堆栈中。
我无法弄清楚如何读取所有不同的数据类型。
数据格式化:
(String)Produce, (String) Type, (String) Sold By [quantity], (float) price, (int) In Stock [quantity].
我怎样才能读取这些不同的数据类型并将它们保存到我的产品项目结构中。
struct produce_Item
{
char produce[20];
char type[20];
char sold_By[20];
float price;
int quantity_In_Stock;
struct produce_Item *next;
}
最佳答案
读取链接列表的典型方法是创建一个临时头节点并仅使用其 .next
字段。
#include <stdlib.h>
...
struct produce_Item Head;
struct produce_Item *p = &Head;
p->next = NULL;
然后循环遍历该文件。虽然这是另一个步骤,但如果通过首先使用 fgets()
读取一行来完成输入,事情会容易得多。然后根据需要使用 sscanf()
或 strtok()
、strtol()
等解析该行。扫描成功完成后,为新节点分配内存,将数据保存在其中并前进p
。
FILE *file;
char buf[100];
while (fgets(buf, sizeof buf, file) != NULL) {
struct produce_Item Item;
if (5 != sscanf(buf, "%19s ,%19s ,%19s ,%f ,%d", Item.produce, Item.type,
Item.sold_By, &Item.price, &Item.quantity_In_Stock)) Handle_BadData();
Item.next = NULL;
// At this point, all 6 fields are set.
struct produce_Item *Next = malloc(sizeof *Next);
if (Next == NULL) Handle_OOM(); // Out of memory
*Next = Item; // Copy Item to *Next
// Advance p
// Notice that the first time this executes, it set Head.next
p->next = Next;
p = Next;
}
return Head.next; // The head of the list
关于c - C中从文件中读取各种形式的数据并存储在链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442444/