我正在研究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