【问题标题】:Reading characters from a text file in c and storing in 2d array problems从c中的文本文件中读取字符并存储在二维数组中的问题
【发布时间】:2017-03-30 03:49:48
【问题描述】:

下面的代码在命令行中给出了 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;
}

【问题讨论】:

  • fscanf(f,"%c",&amp;matrix[i][j]); --> fscanf(f," %c",&amp;matrix[i][j]); ?显示文件示例。
  • 是的,非常感谢。出于好奇,这有什么不同?
  • 跳过前面的空格(换行符)。

标签: c arrays file matrix multidimensional-array


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多