#include<stdlib.h>
#include<stdio.h>
int main() {
FILE* file = fopen ("fourth.txt", "r");
int i = 0;
int rows=0;
int rows2=0;
int columns=0;
int counter=0;
int length=0;
int multiply=0;
fscanf (file, "%d", &i);
rows=i;
printf("the rows are %d\n", i);
int matrix[rows][rows];
length=rows*rows;
if (rows<=0) {
printf("error, this file cannot be processed");
return 0;
}
do
{
if (fscanf(file, "%d", &i)==1) {
if (counter<length) {
matrix[rows2][columns]=i;
counter++;
columns++;
if (columns==rows) {
rows2++;
columns=0;
}
}
multiply=i;
}
} while (!feof(file));
fclose (file);
for ( int c = 0; c < rows; c++ ) {
for ( int j = 0; j < rows; j++ ) {
printf("matrix[%d][%d] = %d\n", c,j, matrix[c][j] );
}
}
printf("the multiply is %d", multiply);
我正在尝试创建矩阵指数(换句话说矩阵乘法)。然而,在我执行实际的数学过程之前,我必须从一个 txt 文件中读取数字作为输入并将它们存储在一个二维数组中。上面是我到目前为止的代码,但是,我很难将数字实际输入到数组中,因为当我在最后测试我的二维数组时,我得到了奇怪的结果。
例如: 1. 输入:
3
123
456
789
2
3 表示行数,对于这个特定的二维数组,它与列数相同,因为矩阵是正方形的,这意味着 所有行和列都相同。
2 代表指数,这是我必须将原始矩阵乘以自身的次数。
但是我的输出是
matrix[0][0] = 123
matrix[0][1] = 456,
matrix[0][2] = 789
matrix[1][0] = 2
matrix[1][1] = 4214800
matrix[1][2] = 0
matrix[2][0] = 3
matrix[2][1] = 0
matrix[2][2] = 0
预期输出必须是:
123
456
789
二维数组
有什么原因吗?
此外,我将如何修改代码,以便无论 txt 文件中关于不同行和列的输入是什么,我仍然可以格式化正确的二维数组。谢谢
最佳答案
在您的输入文本文件中,一行中的数字没有以任何方式分隔。如果您需要多位数字,请考虑用空格或分号等符号分隔它们。
如果矩阵只有一位整数(即从 0 到 9 的数字),那就没问题。
但如果一行中有 3 个数字,比如 21、13 和 4,那么在输入文件中它将只是 21134
。
无法确定它是 211,3,4 还是 21,1,34 还是 2,113,4 还是......
在程序中使用 fscanf()
,每个 %d
将读取整行,将其视为单个数字并将其分配给变量 我
。
而不是先将大小读入i
,然后像这样将其复制到rows
fscanf (file, "%d", &i);
rows=i;
你可以直接读入行
fscanf( file, "%d", &rows);
然后读取像这样的值
for(rows2=0; rows2<rows; ++rows2)
{
if( fscanf(file, "%1d%1d%1d", &matrix[rows2][0], &matrix[rows2][1], &matrix[rows2][2]) != 3)
{
perror("Error");
break;
}
}
然后在最后读取multiply
的值
fscanf(file, "%d", &multiply);
您可以检查fscanf()
的返回值来检查是否有错误发生。
您使用了 !feof(file)
来检查文件结尾。了解不多看看here .
关于c - 将文本文件输入到c中的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500245/