【问题标题】:how to copy from text file to struct using fscanf如何使用 fscanf 从文本文件复制到结构
【发布时间】:2018-05-23 20:29:56
【问题描述】:
    #include <stdio.h>
#include <stdlib.h>



typedef struct Student{
char nume[30];
char prenume[30];
float medie;
}Student;

int main()
{   FILE *st= fopen("input.txt","r");
    Student a[10];
    int i;
    for(i=0;i<10;i++)
        fscanf(st,"%s %s %f",a[i].nume,a[i].prenume,a[i].medie);
    fclose(st);
    return 0;
}

这应该从列表中读取名字、姓氏和数字,为什么会崩溃?

列表如下所示:

ALEXANDRU Tudor 2.23
AMUZA Marius 2.15
CELCAN Alexandra 2.29
KONRAD Eric 2.15
...

【问题讨论】:

  • fscanf 想要变量的地址(不是他的值),将 float 成员的 a[i].medie 更改为 &amp;a[i].medie
  • fopen()fscanf()的返回值是多少?每当您使用此类函数并忽略返回值时,您很可能会被问到同样的问题。

标签: c list text scanf


【解决方案1】:

几乎可以肯定是因为您将 a[i].medie(浮点数的值)而不是 &a[i].medie(浮点数的地址)传递给 fscanf()。

但是如果文件 input.txt 不存在或不可读,你也会崩溃,因为你不检查 fopen() 的错误返回

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2013-09-04
    相关资源
    最近更新 更多