【问题标题】:Reading a text file into 2d array将文本文件读入二维数组
【发布时间】:2013-03-11 18:21:55
【问题描述】:

我有一个文本文件,其行和列中只有随机字母。我想做的就是制作一个二维数组,这样它就是puzzle[i][j],如果我放printf("%c", puzzle[5][4]);,它只会给我第4行和第3列字符(因为它在数组中从0开始)。到目前为止,这是我的代码。

#define MAXROWS     60
#define MAXCOLS     60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main()
{
    FILE *TableFilePtr;
    char TableFileName[100];
    char PuzzleFileName[100];
    char puzzle[MAXROWS][MAXCOLS];
    printf("Please enter the table file name: ");
    scanf("%s",TableFileName);

    TableFilePtr=fopen(TableFileName, "r");

    if(TableFilePtr == NULL)
    {
        printf("Can't open %s", TableFileName);
        exit(EXIT_FAILURE);
    }

    char words;
    int n;
    n=0;
    int i,j,row,col;
    int rowcount, colcount;
    printf("\n how many rows and colums are there?  separate by a space: ");
    scanf("%d %d",&row, &col);
    /*  while(fscanf(TableFilePtr,"%c",&words)!= EOF)
    {
        printf("%c",words);
    }
    */

    /*for (colcount=0;colcount<col;colcount++)
    {
        for (rowcount=0;rowcount<row;rowcount++)
        {
            printf("%c ",words);
        }
    printf("\n");
    }
    */


    for(i=0;i<row;i++){
        for(j=0;j<col;j++){
            fscanf(TableFilePtr, "%c %s\n",&puzzle[i]][j]);
                //puzzle[i][j]=words;
    //          printf("%c ", puzzle[i][j]);
        }
        printf("\n");
    }


}

最后的注释区域(只是开始部分)用于在编译器中简单地打印出文本文件。不过,我想让它成为二维数组。

for(colcount=0;colcount<col;colcount++){...}

【问题讨论】:

  • 你混淆了你对数组索引的理解,这是一个错字吗?
  • 请注意,puzzle[5][4] 打印的是第六行第五列的值,而不是第四行第三列的值——正是因为索引从 0 开始。

标签: c file multidimensional-array scanf


【解决方案1】:

我会做这样的事情(我没有使用你所有的确切变量名,但你明白了):

    char puzzle[MAXROWS][MAXCOLS], line[MAXCOLS];
    FILE *infile;
    int cols = 0, rows=0;

    /* ... */

    infile = fopen(TableFileName, "r");

    while(fgets(line, sizeof line, infile) != NULL)
    {
        for(cols=0; cols<(strlen(line)-1); ++cols)
        {
            puzzle[rows][cols] = line[cols];
        }
        /* I'd give myself enough room in the 2d array for a NULL char in 
           the last col of every row.  You can check for it later to make sure
           you're not going out of bounds. You could also 
           printf("%s\n", puzzle[row]); to print an entire row */
        puzzle[rows][cols] = '\0';
        ++rows;
    }

编辑:更短的版本将在每行的末尾有换行符和 NULL 字符,除非您手动将它们选中。您可能需要调整拼图[][] (使用 MAXCOLS +/- n 或类似的东西)以使其适合您。

    for(c=0; c<MAXROWS; ++c){
        fgets(puzzle[rows], sizeof puzzle[rows], infile);
    }

在循环结束时,puzzle[x][y] 应该是输入文件中的二维字符数组。希望对您有所帮助。

【讨论】:

  • 这是 C 表示数组索引越界(通常)。请记住,计数从 0 开始,因此如果您声明 int myArray[10],则元素为 0-9。如果您尝试访问myArray[10],则会出现 seg err。
  • 这就是我所说的You may have to tweak puzzle[][] (use MAXCOLS +/- n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2020-07-08
  • 2019-03-24
  • 1970-01-01
相关资源
最近更新 更多