简体   繁体   English

在2D阵列解决方案中读取txt文件

[英]read txt file in 2D array solution

i write this code to read a txt file into a 2D array and it's work fine ,but in my input txt i have a 8*8 matrix in the output thay show to me that i have a 37 cols 我写这段代码以将txt文件读入2D数组,并且工作正常,但是在我的输入txt中,我在输出中有8 * 8矩阵,向我显示我有37个col

#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;
}

my input normally : 我的输入通常:

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 

and the output image is : 输出的图像是: 在此处输入图片说明 someone can help please? 有人可以帮忙吗?

That's funny, I get - 很好笑,我得到-

number of rows is 8
number of columns is 29

The problem is that thanks to using getc, you count the number of actual characters in the text file, when you read 255 for eg, that's not really a single char with that value, it's 3 chars with the values 50 ('2'), 53 ('5') and 53 ('5'). 问题是,由于使用了getc,您可以计算文本文件中的实际字符数,例如,当您读取255时,它实际上不是具有该值的单个字符,而是3个字符,其值为50('2') ,53('5')和53('5')。 You'll also count spaces here (which is probably why I got a different results than you did) 您还将在此处计算空格(这可能是为什么我得到与您不同的结果的原因)

You should read them as integers (fscanf for eg), or parse them as such according to the acceptable delimiters (space and newlines in this case, I presume), and only then advance your counters accordingly. 您应该将它们读取为整数(例如,为fscanf),或者根据可接受的分隔符(在这种情况下,我假设是空格和换行符)将其解析为整数,然后才相应地增加计数器。 Alternatively, you can compact your files to a binary format and forget about all the hassle with spaces and newline, one byte per character. 另外,您也可以将文件压缩为二进制格式,而不必担心空格和换行符的麻烦,每个字符一个字节。 They won't be as readable though. 它们将不那么可读。

Also note that your code assumes a fixed column count per line, better be sure it's always the case 另请注意,您的代码假设每行的列数是固定的,因此最好确保始终如此

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM