c - 通过从文本文件中读取数字来生成链接列表

标签 c data-structures linked-list

我想从文本文件中读取数字并动态创建一个链接列表,虽然我能够做到这一点,但最后一个值为 0 的节点也被添加到列表中。我该如何纠正这个问题?另外,如果我愿意,我应该能够添加值 0,但不能以这种方式。

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct node {
      int data;
      struct node *next;
    }node;


    int main(int argc, char const *argv[]) {

      FILE *fp = fopen("data.txt", "r");

      node *prev = NULL;
      while(!feof(fp)){
        node *curr = malloc(sizeof(node));

        fscanf(fp, "%d", &(curr->data));           
        fprintf(stdout, "%d-->", curr->data);

        if(prev != NULL){
          prev->next = curr;
        }
        prev = curr;
      }
      printf("NULL\n");

      fclose(fp);
      return 0;
    }

输入文件是这一列整数 1 5 2 3 6 4

输出是这样的,0不是输入的一部分 1-->5-->2-->3-->6-->4-->0-->NULL

最佳答案

根据评论,您使用 while (!feof(fp)) 是错误的。如果您使用fscanf,则应检查返回(例如== 1)以确定转换成功或失败。您还应该将该值读入临时值(而不是您的列表数据),以便您可以在将其分配给列表之前验证该数字。

将它们放在一起,您可以执行类似以下操作(注意:如果没有,代码会从作为第一个参数传递的文件名(或从 stdin)读取值给出了论证)

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node *next;
} node;


int main (int argc, char **argv) {

    int tmp = 0;
    node *prev = NULL;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    if (!fp) {  /* validate file is open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fscanf (fp, " %d", &tmp) == 1) {  /* validate conversion to tmp */

        node *curr = malloc (sizeof (node));

        curr->data = tmp;                    /* assign tmp to curr->data */
        fprintf (stdout, "%d-->", curr->data);

        if (prev != NULL) {
            prev->next = curr;
        }
        prev = curr;
    }
    putchar ('\n');

    if (fp != stdin) fclose (fp);  /* close if not reading from stdin */

    return 0;
}

另外,当你只需要一个'\n'时,不要使用printf,没有必要。只需使用 putchar('\n');

仔细查看,如果有疑问请告诉我。

关于c - 通过从文本文件中读取数字来生成链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38406210/

相关文章:

c - 将 char 传递给函数 var 列表不起作用

data-structures - 元组、对和映射之间有什么区别?

c - 指针作为 C 函数中的参数

C语法错误: missing ';' before 'type'

c - 为什么执行 uniq -d 的子进程不打印管道通过标准输入传递的重复项?

c# - Python 从 c# 转换 Calculating CRC8 from 4/5 bytes frame

algorithm - 集合操作的数据结构

java - Hashmap hashtable linkedHashmap 有什么用?

java - 删除链表中的元素

java - 单链表中节点的删除