我需要編寫一個讀取各種文件並將信息存儲到數組中的程序。我將使用雙打執行矩陣乘法。關於文件的格式;第一行包含矩陣的大小。接下來的幾行是矩陣的行,其中每個元素由空格分隔。在不同寬度的文件中使用C中的fscanf
格式:
<number of rows> <number of columns>
<double> <double> ... <double>
<double> <double> ... <double>
.
.
.
<double> <double> ... <double>
下面是幾個例子文件:
3 4
1.20 2.10 4.30 2.10
3.30 3.10 5.20 2.80
1.10 0.60 4.70 4.90
或
5 5
1.20 2.10 4.30 2.10 6.70
3.30 3.10 5.20 2.80 3.20
1.10 0.60 4.70 4.90 9.10
3.30 3.10 5.20 2.80 3.20
1.10 0.60 4.70 4.90 7.10
目前我的代碼如下:
float** readFile(char* fp)
{
float** matrix = (float**)malloc(M*N*sizeof(float));
fp = fopen(fp, "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open the file\n");
exit(1)
}
int i = 0;
int m, n;
fscanf(fp, "%d %d", m, n);
while (fscanf(fp, "");
{
i++;
}
fclose(fp);
return matrix;
}
和我打電話這樣的功能:
float** A = readFile(argv[1]);
顯然,這將不會在時刻的fscanf讀取文件的工作,因爲缺少論據。我如何使用fscanf將值讀入矩陣?
讀取文件作爲字符串,分析該字符串多少空格有你現在將如何浮動(如果有的話)在線。 – SJuan76