从文本文件中读取数字列表到2d数组

时间:2016-12-05 04:23:24

标签: c arrays multidimensional-array fopen

我正在尝试将文本文件中的数字读入数组。文本文件“snumbers.txt”有5行,每行10个数字,用空格分隔:

public class The_fragment_adapter extends FragmentStatePagerAdapter {

    public int[] the_layouts = {R.layout.page1,R.layout.page2};

    public The_fragment_adapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new The_fragment();
    }

    @Override
    public int getCount() {
        return the_layouts.length;
    }
}

我的代码:

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; } ,我该怎么做呢,它会给我数字“23”。

1 个答案:

答案 0 :(得分:0)

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

#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;
  }
}