c中的文本文件(int,string,string和float)的fscanf和fgets

fscanf and fgets for a text file (int, string, string and float) in c

我正在尝试使用一个文本文件创建 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; 
}

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

这里有几个问题:

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

不要分配巨大的 automatic variables on your call stack. A typical call frame should have no more than few kilobytes (and your entire call stack should be less than one or a few megabytes). Use C dynamic memory allocation

C只有一维数组。如果你需要更好的,做一些抽象数据类型(通常,避免数组的数组)。查看 寻找灵感。

仔细阅读documentation of every standard function. You should test the result of fscanf

这里有两个问题:

  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]);

为了避免 "strings" 溢出,您可以通过使用 "%42s" 来告诉 fscanf() 最大扫描量,例如,对于 42 [=17= 的字符串]s(不包括 0-终止 char)。


求解2:

使 note 成为 double 并执行

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