[英]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", ¬e[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。 我究竟做錯了什么? 謝謝 ! :)
這里有兩個問題:
混合使用fscanf()
和fgets()
是一個壞主意,因為前者在一行的一部分上工作而后者在整行上工作。
float
不如您預期的那么精確。
解決1:
fscanf(donnees, "%d", &num[n]);
fscanf(donnees, "%s", nom[n]);
fscanf(donnees, "%s", pre[n]);
fscanf(donnees, "%f\n", ¬e[n]);
為了避免溢出“字符串”,您可以告訴fscanf()
最多掃描多少個char
,例如,對42個char
的字符串使用"%42s"
(不計算以0
結尾的char
)。
解決2:
使note
為double
並執行
fscanf(donnees,"%lf\n", ¬e[n]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.