c - C中从文件中读取各种形式的数据并存储在链表中

标签 c linked-list stack

我没有看到类似的东西,所以我决定问问自己。我正在尝试为我的一个类编写一个程序,您可以从文件中读取一组有关杂货的数据,并将其存储在堆栈中。

我无法弄清楚如何读取所有不同的数据类型。

数据格式化:

(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/

相关文章:

c - 链接列表不适用于 strtok

c - 在 C 中使用 void 指针模拟通用链表

将中缀表达式转换为后缀表达式,关联性总是从左到右吗?

c - 如何将捕获的数据包存储在 Excel 表中?

无法在 C 中返回正确的 int

c - 堆栈上的字符串 - c 中没有清理的临时字符串

c++ - 删除链表节点的伪代码

java - 一个带有一个参数的构造函数创建两个不同的对象

c++ - 解释这个 C++ 函数如何返回一个数组

c - 为什么我除法时会跳过数字?