我正在研究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矩阵,它读到有一行和三列。
谁能告诉我我做错了什么?
谢谢:)
答案 0 :(得分:1)
感谢大家的建议和一些侦探自己的工作,我解决了我的问题。首先,我输入了错误的文件名(好吧,现在我觉得很傻),其次,我正在以错误的类型读取数据。
谢谢大家的帮助!
答案 1 :(得分:0)
您没有将holdRows和holdColumns的地址传递给fscanf
。您必须将其更改为fscanf(fp, "%li", &holdRows);
和fscanf(fp, "%li", &holdColumns);
。
答案 2 :(得分:0)
%li
转换规范要求long*
作为fscanf()
的匹配参数:您正在传递int
(dbarbosa提出的修正后的int*
)
尝试"%i"
...和printf()
相同。
%lf
需要double
。 matrix
是否由双打组成?
答案 3 :(得分: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中,某些类型的2D数组与&amp;。
的搭配并不好