[英]Reading a matrix text file into a array in c
I have started learning to code in C, and I am stuck at a assignment where I'm supposed to read a file, put the contents in a matrix, and finally print the matrix. 我已经开始学习用C语言编写代码了,我陷入了一个我应该读取文件,将内容放在矩阵中,最后打印矩阵的任务。
The input file contains: 输入文件包含:
------01-1
1--------1
--0-1-----
----0-----
------0--1
-----1--1-
------0--0
0---------
--11-----1
0-1-----0-
This is the code that I have written so far: 这是我到目前为止编写的代码:
int main()
{
FILE *filename = fopen("file.txt","r");
int matrix[10][10];
int c;
for(int i =0; i < 10; i++)
{
for(int j=0; j<10; j++)
{
c = fgetc(filename);
if(c == '1')
{
matrix[i][j] = 1;
}
else if(c == '0')
{
matrix[i][j] = 0;
}
}
}
for(int a = 0; a < 10; a++)
{
for(int b = 0; b < 10; b++)
{
printf("%d", matrix[a][b]);
}
printf("\n");
}
}
the output: 输出:
-520092443803-520092443-12480181
2686620131463841127199806539638031616085
1316435226866683164344001-520092443011
51119868016113146336314633624404833019927382943080192
26869241998418816-1123324798-2268660019980688424308334426866161992765860
0019927658711830833442686648199276586030801920
1-8756571168119980461561998099927-13626866284
0175821461101992769785308335604200816026866681992735205
199343520826867321992749998819927700401992769850-875656752419907241990720
11268674426869241992847904-1121896548-2119927710210
Press any key to continue.
My guess with the output is that it doesn't add the c
value into the matrix. 我对输出的猜测是,它不会将
c
值添加到矩阵中。 So it prints a "empty" array; 因此它打印出一个“空”数组; the empty array leads to weird numbers?
空数组会导致数字怪异?
I know that I'm reading characters from the text file. 我知道我正在从文本文件中读取字符。 So I need to convert them to
int
values. 所以我需要将它们转换为
int
值。
But why does my code go wrong and where does it go wrong? 但是,为什么我的代码出错了,哪里出错了?
Initialize the matrix 初始化矩阵
int matrix[10][10] = {0};
Handle input other than 0 and 1 处理0和1以外的输入
What else do we need to handle: 我们还需要处理什么:
-
input: Save some other number for ex: 2 or -1 -
输入:保存其他一些数字,例如:2或-1 c = fgetc(filename);
if(c == '1')
{
matrix[i][j] = 1;
}
else if(c == '0')
{
matrix[i][j] = 0;
}
else if(c == '-')
{
matrix[i][j] = -1; /* Special number for - */
}
else if(c == EOF)
{
return -1; /* End of file handling */
}
else
{
--j; /* Ignore this character and enter into loop again */
/* Although modifying loop controlling var inside is not a good habit */
/* For this small module, it should be fine */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.