c - 将文本文件读入二维数组

标签 c file multidimensional-array scanf

我有一个文本文件,行和列中只有随机字母。我想做的就是制作一个二维数组,这样如果我把 printf("%c", puzzle[5][4]) 放在其中,它就是 puzzle[i][j] ; 它只会给我第 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++){...}

最佳答案

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

    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 字符,除非您手动将它们删除。您可能需要调整 puzzle[][] (使用 MAXCOLS +/- n 或类似的东西)才能使其适合您。

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

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

关于c - 将文本文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15561119/

相关文章:

C 随机数生成器 - 它的变化如此缓慢。该怎么办?

c - 与 atoi() 相反的功能?

c# - 为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名?

PHP - 多维 SESSION 数组对性能来说是好是坏?

c - 对 pesquisar_bin 的 undefined reference

c - `scanf("%*[^\n]%*c")` 是什么意思?

java - 检测何时使用 java 访问/读取文件

c - 为什么文本文件中会出现多余的字符?

用于多维 C 数组的 C++ 迭代器

c - C语言中如何输入多字字符串