我正在研究C中的項目,這需要我從txt文件中讀取矩陣值。前兩行是行數和列數,剩下的就是實際的矩陣數據。需要幫助從C中的txt文件讀取
例如,這樣的事情:
2
2
1.0 2.0
3.0 4.0
我寫的是給了我一些問題的代碼。這裏有一個片段:
matrix read(char* file){
FILE *fp;
printf("check 1\n");
fp = fopen(file,"r");
printf("file opened\n");
// Make the new matrix
matrix result;
printf("matrix created\n");
int counter = 0;
int i;
int j;
int holdRows;
int holdColumns;
if(counter == 0)
{ // read in rows
fscanf(fp, "%li", holdRows);
printf("here is holdRows: %li\n", holdRows);
counter++;
}
if(counter == 1)
{ // read in columns
fscanf(fp, "%li", holdColumns);
printf("here is holdColumns: %li\n", holdColumns);
counter++;
// Now that I know the dimensions, make the matrix
result = newMatrix(holdRows, holdColumns);
}
// For the rest, read in the values
for(i = 0; i < holdRows; i++)
for(j = 0; j < holdColumns; j++)
fscanf(fp, "%lf", &result->matrixData[i][j]);
fclose(fp);
return result;
}
每當我運行此,holdRows和holdColumns不是存儲在txt文件中的值。例如,我嘗試了一個3X4矩陣,它讀取了一行和三列。
誰能告訴我我做錯了什麼?
謝謝:)
這是功課嗎? – Starkey 2010-09-12 17:50:20
爲什麼你有'計數器'和這些'如果'與'計數器'? – dbarbosa 2010-09-12 17:51:49
與上面相同.....計數器變量似乎完全沒有必要。 – loxxy 2010-09-12 17:54:54