2010-09-12 87 views
1

我正在研究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矩陣,它讀取了一行和三列。

誰能告訴我我做錯了什麼?

謝謝:)

+5

這是功課嗎? – Starkey 2010-09-12 17:50:20

+0

爲什麼你有'計數器'和這些'如果'與'計數器'? – dbarbosa 2010-09-12 17:51:49

+0

與上面相同.....計數器變量似乎完全沒有必要。 – loxxy 2010-09-12 17:54:54

回答

0

你不及格holdRows和holdColumns的地址fscanf。您必須將它們更改爲fscanf(fp, "%li", &holdRows);fscanf(fp, "%li", &holdColumns);

+0

我切換到&holdRows和&holdColumns,但讀入的數據仍然不正確。謝謝,雖然:) – user445691 2010-09-12 17:55:20

0

%li轉換規範要求long*作爲參數匹配fscanf():你傳遞一個intint*由dbarbosa提出修正後)。

嘗試"%i" ...和printf()相同。


%lf預計double。是雙打的matrix

+0

是的,矩陣是由雙打。 – user445691 2010-09-12 18:04:33

0

嘗試更換:

for(i = 0; i < holdRows; i++) 
     for(j = 0; j < holdColumns; j++) 
      fscanf(fp, "%lf", &result->matrixData[i][j]); 

double temp; 
for(i = 0; i < holdRows; i++) 
     for(j = 0; j < holdColumns; j++) { 
      fscanf(fp, "%lf", &temp); 
      result->matrixData[i][j] = temp; 
     } 

我似乎記得,在C某些類型的二維數組的不玩好與&。

+0

這可能會起作用,但我不確定,因爲我仍然在讀取holdRows和holdColumns的錯誤值,並且holdColumns是7位數字,所以循環持續很長時間。 – user445691 2010-09-12 18:22:27

+0

@buzzbuzz:如果出現錯誤,測試'scanf'的返回值並提前退出循環。 – pmg 2010-09-12 18:30:33

1

感謝大家的建議以及我自己的一些偵探工作,我解決了我的問題。首先,我輸入了錯誤的文件名(好吧,現在我感覺很傻),其次,我正在讀取錯誤類型的數據。

謝謝大家的幫助!

+0

您返回一個局部變量,該函數將無法工作。 – user411313 2010-09-12 21:38:00

+0

@ user411313:傳遞一個本地變量通常工作,返回一個局部變量的地址是破碎的概念。 – 2011-05-05 09:35:20