reading data from files and store them in vector<vector<pair<int,int>>> in c++

Viewed 115

I have a file say data.txt in which data is as like below;

1   80,982 163,8164
2   42,1689 127,9365 5,8026
3   57,1239 101,3381 43,731 115,7827 17,7002 72,794 150,4539
4   162,3924 70,5285 195,2490 72,6508 126,2625 121,7639 31,399 118,3626 90,9446 127,6808

i have a container as vector<vector<pair<int,int>>>Graph(100), by reading above data I want to perform operation as Graph[1].push_back({80,982}) , Graph[1].push_back({163,864}).

similarly Graph[2].push_back({42,1689}), Graph[2].push_back({127,9365}), Graph[2].push_back({5,8026}). and so on for the third row, till it gets end. I have little idea I can use ifstream file("data.txt"); and then taking a string variable string str and proceed in this way.

 while (getline(file, str)) {
        //perform operation
        // stringstream ss(str) can be used to parse commas
        //how to deal with variable length.
    }

please help me how can I do the above task. thank you so much.

1 Answers

To read lines of variable length, you must read the whole line at once, then parse it.

To read the whole line, use getline:

string str;
getline(cin, str);

(This is one of several variants of getline.)

Then to parse it, you could iterate over it, looking for spaces and commas, and converting numerals into numbers, but that is very tedious. C++ allows the use of stringstream, which is easier:

#include <sstream>

std::stringstream ss;
ss << str;

int n=0;
string word;
while(ss >> word)
  cout << ++n << " " << word << endl;
Related