我编写此代码将 txt 文件读入 2D 数组,并且工作正常,但在我的输入 txt 中,我在输出中有一个 8*8 矩阵,它向我显示我有 37 列
#include <stdio.h>
int main()
{
int c, i, j, row, col, nl, cr;
row = col = nl = cr = 0;
FILE *fp = fopen("image.txt", "r");
// Figure out how many rows and columns the text file has
while ((c = getc(fp)) != EOF)
{
if (c == '\n')
nl++;
if (c == '\r')
cr++;
col++;
if (c == '\n')
row++;
putchar(c);
}
col = (col - (nl + cr));
col = (int) (col/row);
printf("\nnumber of rows is %d\n", row);
printf("number of columns is %d\n\n", col);
return 0;
}
我的输入正常:
255 50 9 50 1 50 50 1
50 255 50 50 50 50 50 50
50 50 255 50 50 50 50 50
8 50 50 255 50 50 50 50
50 50 50 50 255 50 50 50
50 50 50 50 50 255 50 50
1 50 50 50 50 50 255 50
2 50 50 50 50 50 50 255
输出图像为: 有人可以帮忙吗?
最佳答案
这很有趣,我明白 -
number of rows is 8
number of columns is 29
问题是,由于使用了 getc,您可以计算文本文件中的实际字符数,例如,当您读取 255 时,这实际上并不是具有该值的单个字符,而是具有值 50 (' 2')、53('5')和53('5')。您还将在这里计算空格(这可能就是为什么我得到的结果与您不同的原因)
您应该将它们读取为整数(例如 fscanf),或者根据可接受的分隔符(我认为在本例中为空格和换行符)解析它们,然后才相应地推进计数器。或者,您可以将文件压缩为二进制格式,并忘记空格和换行符(每个字符一个字节)的所有麻烦。但它们的可读性不那么好。
另请注意,您的代码假设每行有固定的列数,最好确保始终如此
关于c - 读取二维数组中的txt文件解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18943282/