从文本文件读取到2D数组

时间:2019-09-01 00:01:23

标签: c++ arrays multidimensional-array

我有一个文本文件,其中包含几行整数,每个整数之间用空格隔开,我想将这些整数读入数组,其中每一行都是数组的第一维,每个整数该行上的内容将保存到第二维。

我的文本文件看起来像这样:

  

0 1 2 3 4 5 6 7 8 9

     

9 0 1 2 3 4 5 6 7 8

     

8 9 0 1 2 3 4 5 6 7

     

7 8 9 0 1 2 3 4 5 6

     

6 7 8 9 0 1 2 3 4 5

     

5 6 7 8 9 0 1 2 3 4

     

4 5 6 7 8 9 0 1 2 3

     

3 4 5 6 7 8 9 0 1 2

     

2 3 4 5 6 7 8 9 0 1

所以这是我到目前为止尝试过的,但是看起来很烂

  string array[30][30]; //row, column
  ifstream myfile("numbers.txt");

  int row = 0;
  int col = 0;
  while(!myfile.eof())
  {
      //Extract columns
      while(getline(myfile, array[row][col]),!'\n')
      {
         getline(myfile,array[row][col],' ');
        col++;
      }
    //Extract rows
    //    getline(myfile,array[row][col],'\n');

     //   row++;

        cout<<  row << '\t' <<  array[row][col] <<  "\n";
  }

1 个答案:

答案 0 :(得分:1)

while(!myfile.eof())很少是一个好主意。阅读完最后一行后,该条件仍将评估为true。仅当您尝试读取文件中最后一个字符以外的内容时,才会设置eof()。另外,string array[30][30]是一个硬编码的30x30 C样式数组,不适合您的数据。取而代之的是,使用C ++容器std::vector(可以嵌套在任意尺寸的维度中)动态添加数字。

假设numbers.txt中没有空行,您可以这样做:

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdexcept>

std::vector<std::vector<int>> get_2d_array_of_ints_from_stream(std::istream& is) {
    std::vector<std::vector<int>> return_value;

    std::string line;
    while(std::getline(is, line)) {   // if this fails, EOF was found or there was an error
        std::istringstream iss(line); // put the line in a stringstream to extract numbers
        int value;                    // temporary used for extraction
        std::vector<int> line_values; // all values on this line
        while(iss >> value)           // extract like when reading an int from std::cin
            line_values.push_back(value); // put the value in the 1D (line) vector
        // check that all lines have the same amount of numbers
        if(return_value.size() && return_value[0].size()!=line_values.size())
            throw std::runtime_error("file format error");
        return_value.emplace_back(std::move(line_values)); // move this line's vector<int>
                                                           // to the result_value
    }
    return return_value;
}

int main() {
    if(std::ifstream is{"numbers.txt"}; is) {
        try {
            // auto arr2d = get_2d_array_of_ints_from_stream(is);
            // would be the same as:
            std::vector<std::vector<int>> arr2d = get_2d_array_of_ints_from_stream(is);
            std::cout << "Got a " << arr2d[0].size() << "x" << arr2d.size() << " array\n";
            for(const std::vector<int>& line_values : arr2d) {
                for(int value : line_values) {
                    std::cout << " " << value;
                }
                std::cout << "\n";
            }
            std::cout << "--\n";
            // or you can use the subscript style of arrays
            for(size_t y = 0; y < arr2d.size(); ++y) {
                for(size_t x = 0; x < arr2d[y].size(); ++x) {
                    std::cout << " " << arr2d[y][x];
                }
                std::cout << "\n";
            }
        } catch(const std::exception& ex) {
            std::cerr << "Exception: " << ex.what() << "\n";
        }
    }
}
相关问题