【问题标题】:C programming, fscanf only inputs the last elementC编程,fscanf只输入最后一个元素
【发布时间】:2018-01-22 16:55:50
【问题描述】:

我试图从一个文件中获取多个元素并将其放入我的数组链表中,但它只输入文件的最后一个元素。

文件里面是

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

这是我的代码

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

void insert(node **a)
{
    int temp,elem;
    node *tempstruct;
    tempstruct = (*node)malloc(sizeof(struct node));
    FILE *fp;
    if(fp = fopen("input.txt","r")){
        while(fscanf(fp,"%d",&elem)==1){
            temp = elem%10;
            tempstruct->elem = elem;
            tempstruct->next = a[temp];
            a[temp] = tempstruct;
        }
    }
}

预期的输出应该是

A[0]   10
A[1]   11   1
A[2]   12   2 
A[3]   13   3 
A[4]   14   4
A[5]   15   5 
A[6]   16   6
A[7]   17   7
A[8]   18   8
A[9]   19   9

但我得到的是

A[0]   19
A[1]   19
A[2]   19
A[3]   19
A[4]   19
A[5]   19
A[6]   19
A[7]   19
A[8]   19
A[9]   19

我试图将元素放入与其个位对应的索引中,但它所放入的只是最后一个元素,即 19。

【问题讨论】:

  • 您的代码无法编译。例如(*node)temp = %elem;
  • 尽量避免类型转换malloc的返回值。
  • 您尝试调试太多。首先,了解如何从文件中读取数据。其次,弄清楚如何将这些项目分配给node
  • 很抱歉,获取个位数的索引是 temp = elem%10

标签: c file linked-list


【解决方案1】:

您只调用一次malloc,因此您最终会遇到数组中的所有元素都指向同一个对象的情况。相反,您应该为每次成功的扫描调用 malloc

喜欢:

void insert(node **a)
{
    int temp,elem;
    node *tempstruct;
    FILE *fp;
    if(fp = fopen("input.txt","r")){
        while(fscanf(fp,"%d",&elem)==1){
            tempstruct = malloc(sizeof(struct node));  // malloc inside the loop
            temp = elem % 10;      // Find the index where the new object shall be added
            tempstruct->elem = elem;
            tempstruct->next = a[temp];
            a[temp] = tempstruct;
        }
    }
}

【讨论】:

  • 代码不稳定:尚不清楚a[] 的糊状程度如何。
  • @chux 是的。不幸的是,OP 从未发布过完整的代码示例。然而,从“预期输出”来看,假设a[] 有 10 个元素,即 10 个链表,其中数据根据数据的最后一位排序,似乎是公平的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2019-11-29
  • 2021-05-16
  • 2017-04-08
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多