簡體   English   中英

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

[英]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; 
}

問題是,我敢肯定,對於初學者來說,有更好的方法來創建數組。 另外,浮點數有問題,當我打印f時,小數點不正確。 例如,78.7變為78.699997。 我究竟做錯了什么? 謝謝 ! :)

這里有兩個問題:

  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()最多掃描多少個char ,例如,對42個char的字符串使用"%42s" (不計算以0結尾的char )。


解決2:

使notedouble並執行

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

這里有幾個問題:

浮點運算非常棘手。 閱讀浮點gui.de (並記住該URL)。

不要在調用棧上分配巨大的自動變量 一個典型的呼叫幀應不超過幾千字節(並且您的整個呼叫堆棧應少於一或幾兆字節)。 使用C動態內存分配

C只有一維數組。 如果需要更好,請創建一些抽象數據類型(通常應避免使用數組數組)。 看看這個靈感。

仔細閱讀每個標准功能的文檔 您應該測試fscanf的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM