2010-09-12 86 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