[英]Reading float numbers from a file in a special manner
我正在嘗試從2D數組中的文件中讀取數字,我必須跳過第一行和第一列,其余所有內容都必須保存在數組中,我嘗試使用sscanf,fscanf甚至strtok(),但是慘敗 因此,請幫助我解決此問題。 提前感謝,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]){
FILE *f=fopen("Monthly_Rainfall_Himachal.txt","r");
float data[12][12];
int i,j;
char newLine[1000];
fgets(newLine,1000,f);
char* item,waste;
i=0;
while(1)//read file line by line
{
fscanf(f, "%s %f %f %f %f %f %f %f %f %f %f %f %f ", waste, &data[i][0], &data[i][1], &data[i][2], &data[i][3], &data[i][4], &data[i][5], &data[i][6], &data[i][7], &data[i][8], &data[i][9], &data[i][10], &data[i][11]);
i++;
if(feof(f))break;
}
fclose(f);
for(i=0 ;i<12 ;i++){
for(j=0 ;j<12 ;j++){
printf("%.1f\t",data[i][j]);
}
printf("\n");
}
return 0;
}
問題:
您無需檢查fopen
是否成功打開文件,而盲目地假設它成功。
檢查其返回值:
if(f == NULL) { fputs("fopen failed! Exiting...\\n", stderr); return EXIT_FAILURE; }
除了讀取和存儲第一行,您還可以使用scanf
讀取並丟棄它:
scanf("%*[^\\r\\n]"); /* Discard everything until a \\r or \\n */ scanf("%*c"); /* Discard the \\r or \\n as well */ /* You might wanna use the following instead of `scanf("%*c")` if there would be more than one \\r or \\n int c; while((c = getchar()) != '\\n' && c != '\\r' && c != EOF); But note that the next fscanf first uses a `%s` which discards leading whitespace characters already. So, the `scanf("%*c");` or the while `getchar` loop is optional */
item
和一個字符變量waste
。 這兩個都是不必要的。 因此,將其刪除。 在很長的fscanf
行中,您首先嘗試將字符串掃描到一個字符變量中,該變量會調用未定義行為,從而使事情變得混亂。 您還需要檢查其返回值以查看是否成功。
用以下命令替換該fscanf
行:
if(fscanf(f, "%*s") == EOF) { fputs("End Of File! Exiting...\\n", stderr); return EXIT_SUCCESS; } for(j = 0; j < 12; j++) { if(fscanf(f, "%f", &data[i][j]) != 1) { fputs("End Of File or bad input! Exiting...\\n", stderr); return EXIT_SUCCESS; } }
您假定輸入最多12行,但是如果輸入超過12行,由於數組溢出,您的代碼將調用Undefined Behavior。
將i
的值與feof
一起檢查以確保其值不超過11:
if(i >= 12 || feof(f))
注意:我沒有測試任何上述代碼。 如果我弄錯了,請糾正我。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.