将文本文件中的数字列表读入二维数组

Reading a list of numbers from text file into 2d array

我正在尝试将文本文件中的数字读入数组。文本文件 "snumbers.txt" 有 5 行,每行 10 个数字,全部由 space 分隔:

11 10 23 3 23 98 39 12 9 10
10 23 23 23 23 2 2 2 2 2
…etc…

我的代码:

#include <stdio.h>
int main()
{
    FILE *myFile;
    myFile = fopen("snumbers.txt", "r");

    //read file into array
    int numberArray[100][100];
    int i;



}

如果我访问 numberArray[1][1],我该如何做到这一点,它会给我数字“23”。

这是将您的输入文件读入数组的完整代码。我创建了一个 'converter' 来读取字符并将它们转换为数字。假设您在数字之间有一个 space 。您可以按原样使用它或从中学习,以便您可以使用以下示例实施一些解决方案:

#include <stdio.h>
#include <string.h>

int main(void){
  FILE *myFile; // file pointer to read the input file
  int   i,      // helper var , use in the for loop
        n,      // helper var, use to read chars and create numbers
        arr[100][100] , // the 'big' array
        row=0,  // rows in the array
        col,    // columns in the array
        zero=(int)'0';  // helper when converting chars to integers
  char line[512]; // long enough to pickup one line in the input/text file
  myFile=fopen("snumbers.txt","r");
  if (myFile){
        // input file have to have to format of number follow by one not-digit char (like space or comma)
        while(fgets(line,512,myFile)){
                col = 0;        // reset column counter for each row
                n = 0;          // will help in converting digits into decimal number
                for(i=0;i<strlen(line);i++){
                        if(line[i]>='0' && line[i]<='9') n=10*n + (line[i]-zero);
                        else {
                                arr[row][col++]=n;
                                n=0;
                        }
                }
                row++;
        }
        fclose(myFile);

        // we now have a row x col array of integers in the var: arr
        printf("arr[1][1] = %d\n", arr[1][1]); // <-- 23
        printf("arr[0][9] = %d\n", arr[0][9]); // <-- 10
        printf("arr[1][5] = %d\n", arr[1][5]); // <-- 2

  } else {
        printf("Error: unable to open snumbers.txt\n");
        return 1;
  }
}