Reading from .txt file into two dimensional array in c++

Reading from .txt file into two dimensional array in c++

I believe that

istream inputStream;
int myArray[3][5];
for(int i = 0; i < 3; i++)
    for(int j = 0; j < 5; j++)
        istream >> myArray[i][j];

should do what you need.

In your case you can do something like this:

ifstream file { file.txt };
if (!file.is_open()) return -1;

int my_array [3][5]{};
for (int i{}; i != 3; ++i) {
    for (int j{}; j != 5; ++j) {
        file >> my_array[i][j];
    }
}

A much better way is to use std::vector:

vector<int> my_array;
int num { 0 };
while (file >> num)
    my_array.emplace_back(num);

Reading from .txt file into two dimensional array in c++

Leave a Reply

Your email address will not be published.