Read a txt file and store content in lists

Asked

Viewed 190 times

-1

I need to read a large ". txt" file and its contents are in the following format:

1   12
1   13
2   5
2   6

I would like to know if it is possible to read the value of each column and store it in a list, for example:

Ler "1"
Armazenar o "1" numa lista
Ler "12"
Armazenar 12 numa lista
ler "1"
Armazenar "1" na lista
ler "13"
Armazenar 13 na lista
...

And so on and so forth

  • Which C++ library are you using to read the txt file? The logic of this is basically: read the whole file, play in a string, split it into an array to identify the elements of the lists and then go through this array distributing elements.

1 answer

2

To have 2 lists, each containing the numbers of a column the code below can help.

int main() {
    std::ifstream file{"text.txt"};

    std::vector<std::string> columnA;
    std::vector<std::string> columnB;
    std::string string;

    int i = 0;
    while ( !file.eof() ) {
        file >> string;
        if (i++ % 2 == 0) columnA.push_back(string);
        else columnB.push_back(string);
    }

    for (auto s : columnA) std::cout << s << "\n";

    std::cout << "\n";

    for (auto s : columnB) std::cout << s << "\n";

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.