繁体   English   中英

将非偶数行的文本文件读入2D数组

[英]reading a text file of non-even lines into 2D array

对不起,我是C的新手,我很难过。 我有一个输入文本文件,其中包含:

5 3
383 386 287
415 293 335
368 492 149
421 362 27
190 59 263

我试图将其读入2D数组。 我在想的是这个:

FILE * fin = NULL;
fin = fopen("myTestData.txt", "r");
int twod[MAX_ROWS][MAX_COLS];

int i, j, num, row, col;
fscanf(fin, "%d%d", &row, &col);

fclose(fin);

fin = fopen("myTestData.txt", "r");
for(i = 0; i < row; i++)
{
    for(j = 0; j < col; j++)
    {
        fscanf(fin, "%i ", &num);
    twod[i][j] = num;
    }
}

我遇到的问题是在空白的第一行(twod [0] [2])上,它为第二行(383)的第一个整数赋值。 我能做什么才能使[0] [2]获得空值?

谢谢你的帮助

删除关闭的行并重新打开该文件。 在读入行数和列数后,您只需处理剩余的数据,这些数据结构合理 - 大多数作业问题也是如此。

FILE * fin = NULL;
fin = fopen("myTestData.txt", "r");
int twod[MAX_ROWS][MAX_COLS];

int i, j, num, row, col;
fscanf(fin, "%d%d", &row, &col);

//fclose(fin);

//fin = fopen("myTestData.txt", "r");
for(i = 0; i < row; i++)
{
    for(j = 0; j < col; j++)
    {
        fscanf(fin, "%i ", &num);
        twod[i][j] = num;
    }
}

for (i = 0; i < row; i++)
{
    for (j = 0; j < col; j++)
        printf("%d ", twod[i][j]);
    printf("\n");
}
    #include <stdio.h>
    #include <stdlib.h>

    #define NUM_MAX_SIZE 20

    int** get2DArray( int rows, int columns )
    {
        int index = 0, **array = (int**)calloc( rows, sizeof( int* ) );

        for( ; index < rows ; index++ )
        {
            array[ index ] = (int*)calloc( columns, sizeof( int ) );
        }

        return array;
    }


    void print2DArray( int** matrix, int rows, int columns )
    {   
        int x = 0, y = 0;
        for( ; x < rows ; x++)
        {
            for( y = 0 ; y < columns ; y++)
            {
                printf( "%d\t", matrix[x][y] );
            }
            puts("");
        }
    }

    void freeMatrix( int** matrix, int rows )
    {
        rows--;
        for( ; rows > -1 ; rows-- )
        {
            free( matrix[ rows ] );
        }

        free( matrix );
    }

    int main()
    {
        FILE* file = fopen( "input.txt", "r" );

        int rows, columns;

        fscanf( file, "%d", &rows );
        fscanf( file, "%d", &columns );

        int x = 0, y = 0, num , **matrix = get2DArray( rows, columns );

        for( ; x < rows ; x++)
        {
            for( y = 0 ; y < columns ; y++)
            {
                fscanf( file, "%d", &matrix[ x ][ y ] );
            }
        }

        print2DArray( matrix, rows, columns );
        freeMatrix( matrix, rows );

        fclose( file );
        return 0;
    }

暂无
暂无

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

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