-1

I've got a text file which contains several lines of integers, each integer is separated by a space, I want to read these integers into an array, where each new line is the first dimension of the array, and every integer on that line is saved into the second dimension.

My text file looks something like this:

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

So here's what i tried so far, but it looks like a mess

  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";
  }
Leoid9
  • 61
  • 3

1 Answers1

1

while(!myfile.eof()) is rarely a good idea. When you've read your last line, that condition will still evaluate to true. eof() will only be set once you've tried to read beyond the last character in the file. Also, string array[30][30] is a hardcoded 30x30 C style array that doesn't fit your data. Instead, use the C++ container std::vector (that can be nested in as many dimensions as you'd like) to dynamically add numbers.

Assuming that you don't have blank lines in numbers.txt you could do like this:

#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";
        }
    }
}
Ted Lyngmo
  • 37,764
  • 5
  • 23
  • 50
  • Thank you but my assignment requires I use arrays instead. – Leoid9 Sep 01 '19 at 02:03
  • I see. My answer wouldn't have been the same had I known it was for an assignment. Anyway... Are you sure that's a real restriction? I would expect it to be more of a suggestion. If you read about [std::vector](https://en.cppreference.com/w/cpp/container/vector) you shouldn't have any problem motivating why you used that instead. If the teacher flunks you for using what everyone in the business uses to do stuff like this, I'd be surprised. – Ted Lyngmo Sep 01 '19 at 02:12