Kastoli
Kastoli

Reputation: 105

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

So either I'm a complete idiot and this is staring me right in the face, but I just can't seem to find any resources I can understand on google, or here.

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.

Probably used the worst terminology to explain that, sorry.

My text file looks something like this:

100 200 300 400 500
101 202 303 404 505
111 222 333 444 555

And I want the resulting array to be something like this:

int myArray[3][5] = {{100, 200, 300, 400, 500},
                     {101, 202, 303, 404, 505},
                     {111, 222, 333, 444, 555}};

Upvotes: 2

Views: 45452

Answers (2)

Andreas DM
Andreas DM

Reputation: 10998

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);

Upvotes: 1

GMichael
GMichael

Reputation: 2776

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.

Upvotes: 2

Related Questions