【问题标题】:How to open a txt file and allocate its contents to a 2D array?如何打开 txt 文件并将其内容分配给二维数组?
【发布时间】:2022-11-12 22:28:39
【问题描述】:

所以我有一个代表矩阵的 txt 文件。我需要做的是打开它并将其内容分配给一个矩阵。

例如:

在我的 txt 文件中,我有:

 39  -1 -42 -42 
 -6 -46  89  86 
 76 -62  35  92 
-20  24 -10  38 
 52   1 -86  41 

我需要打开一个文件读取其内容并将每个值分别分配到一个矩阵中。

我试过这个,但是,我仍然无法访问单个元素。我正在考虑使用strtok() 将线路分解为令牌作为我的备用计划,但我相信应该有更好的方法。

  int matrix[4][5];

  FILE *files;
  char str[100];


  files = fopen("./matrix-samples/m-5-10-a.txt", "r");
  if(files == NULL) {
    printf("%s\n","error" );
    }
  else{
    for (int i = 0; i < 5; i++) {
      fgets (str, 60, files);
      printf("%s", str);
    }

  }
    return 0;
}

【问题讨论】:

  • 你被困在哪里了?你知道如何打开文件吗?从中读出一行?解析线?这些都是googleable的步骤。
  • 你写了什么代码?您是否使用fopen 打开文件?您是否使用fscanf阅读了第一个数字?你在哪里遇到问题?
  • @yano 哎呀对不起错字
  • 我曾尝试使用 fopen 和 fgets。问题是通过尝试访问单个值然后将其分配给矩阵位置而发生的。 @abelenky

标签: c multidimensional-array io


【解决方案1】:

不要使用strtok。地狱第 9 圈包含 3 个函数:getsscanfstrtok。只是避免它。使用fgets 读取数据,并使用strtol 系列中的内容对其进行解析。例如:

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

#define ROW 5
#define COL 4


static void
die(int row, int col)
{
    fprintf(stderr, "Invalid input in row %d, near column %d
", row, col);
    exit(1);
}

int
main(int argc, char **argv)
{
    const char *path = argc > 1 ? argv[1] : "matrix-samples/m-5-10-a.txt";
    int matrix[ROW][COL];
    FILE *ifp = fopen(path, "r");
    char str[256];
    if( ifp == NULL ){
        perror(path);
        return EXIT_FAILURE;
    }
    int row = 0;
    while( row < ROW && fgets(str, sizeof str, ifp ) != NULL ){
        char *p = str;
        for( int col = 0; *p && col < COL; col += 1 ){
            char *end;
            matrix[row][col] = strtol(p, &end, 10);
            if( ! isspace(*end) ){
                die(row, end - str);
            }
            p = end + 1;
        }
        while( isspace(*p) ){
            p += 1;
        }
        if( *p || p[-1] != '
' ){
            die(row, p - str);
        }
        row += 1;
    }
    if( fgetc(ifp) != EOF ){
        die(row, 0);
    }
    for( int i = 0; i < ROW; i++ ){
        for( int j = 0; j < COL; j++ ){
            printf("%7d", matrix[i][j]);
        }
        putchar('
');
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-02-03
    • 2017-08-13
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多