简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM