从c中的文本文件中读取字符并存储在2d数组问题中

时间:2016-11-16 03:55:17

标签: c arrays file matrix multidimensional-array

下面的代码在命令行中给出了3个参数,文本文件,矩阵中的行数和矩阵中的列数。我传入的文件有10行12列。如果我在命令行中传递10(对于行)和12(对于列),由于某种原因,它会一直输出到第8个索引行和第7个索引列。如果我通过11和13,它将输出完整的矩阵加上最后的@符号。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
    FILE *f;
    int i = 0,j = 0;

    if(argc != 4)
    {
        printf("You did not enter a file name and/or rows/columns.");
    }
    else
    {
        int rows = atoi(argv[2])  ;
        int columns = atoi(argv[3]) ;
        char matrix[rows][columns];

        f = fopen(argv[1], "r");
        if(f == NULL)
        {
            printf("Invalid File");
        }
        else
        {
            for(i = 0 ; i < rows ; i++)
            {
                for(j = 0 ; j < columns ; j++)
                {
                    fscanf(f,"%c",&matrix[i][j]);               
                    printf("%c", matrix[i][j]);
                }       
            }
        }

        fclose(f);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

您没有指定文件的结构,因此我假设您不小心读取任何现有的空白字符(例如空格,换行符,制表符等)。

使用" %c"代替fscanf。注意'%'之前的额外空格,这很重要。它告诉fscanf忽略任何空白字符。