【问题标题】:fscanf and fgets for a text file (int, string, string and float) in cc 中文本文件(int、string、string 和 float)的 fscanf 和 fgets
【发布时间】:2018-05-17 00:29:33
【问题描述】:

我正在尝试使用文本文件创建 4 个数组。文本文件如下所示:

1000 Docteur             Albert              65.5
1001 Solo                Hanz                23.4
1002 Caillou             Frederic            78.7
…

代码:

void creer (int num[], char pre[][TAILLE_NP+1], char nom[][TAILLE_NP+1], 
float note[], int * nb ){

  int  n = 0, i; /*nb personnes*/

  FILE *donnees = fopen("notes.txt", "r");

  if(!donnees){
    printf("Erreur ouverture de fichier\n");
    exit(0);
  }

  while (!feof(donnees)){

    fscanf(donnees,"%d", &num [n]);
    fgets(nom[n], TAILLE_NP+1, donnees);
    fgets(pre[n], TAILLE_NP+1, donnees);
    fscanf(donnees,"%f\n", &note[n]);

    printf("%d %s %s %f\n",num[n], nom[n], pre[n], note[n]);
    n++;
    }

  fclose (donnees);

  *nb = n ;
  }


int main() {

  int num[MAX_NUM];
  int nbEle;

  char pre[MAX_NUM][TAILLE_NP+1],
       nom[MAX_NUM][TAILLE_NP+1];

  float note[MAX_NUM];

  creer (num, pre, nom, note, &nbEle);

  printf("%s", pre[2]); //test

  return 0; 
}

问题是,我确信有更好的方法来创建数组,我是初学者。另外,浮点数有问题,当我 printf 时小数不正确。例如,78.7 变为 78.699997。 我究竟做错了什么? 谢谢 ! :)

【问题讨论】:

    标签: c string file scanf fgets


    【解决方案1】:

    这里有两个问题:

    1. 混合使用 fscanf() 和 fgets() 是个坏主意,因为前者适用于部分行,而后者适用于整行。

    2. float 并不像您预期​​的那么精确。


    解决1:

    fscanf(donnees, "%d", &num[n]);
    fscanf(donnees, "%s", nom[n]);
    fscanf(donnees, "%s", pre[n]);
    fscanf(donnees, "%f\n", &note[n]);
    

    为避免溢出“字符串”,您可以告诉fscanf() 最多扫描多少,例如,使用"%42s" 表示42 个chars 的字符串(不包括0-终止char)。


    解决2:

    将note 设为doubles 并执行

    fscanf(donnees,"%lf\n", &note[n]);
    

    【讨论】:

    • 解决 2 成功!谢谢。但是解决1没有用。当我更改代码时,执行非常混乱,note[n] 为 0.0000
    • @SamuelGirard:“没有工作”是什么意思,拜托?
    • 没关系,这只是 printf。忘记将 %f 更改为 %lf。非常感谢!
    • @SamuelGirard 有否需要在打印doubles时使用长度修饰符l。没有它,它应该正确地工作。
    【解决方案2】:

    这里有几个问题:

    浮点非常棘手。阅读floating-point-gui.de(并记住该网址)。

    不要在您的call stack 上分配大量的automatic variables。一个典型的调用帧应该不超过几千字节(整个调用堆栈应该小于一或几兆字节)。使用C dynamic memory allocation。

    C 只有一维数组。如果您需要更好,请制作一些抽象数据类型(通常,避免使用数组的数组)。查看this 以获得灵感。

    仔细阅读每个标准函数的documentation。你应该测试fscanf的结果。

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 1970-01-01
      • 2016-08-11
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多