Reading value from a file into vector<vector<int>>

I have a input file which has an integer seperated by comma across multiple lines.
e.g - 1,2,3,4
2,3,4,5
4,5,6,7
I want to read those value and assign it into vector<vector<int>> and print it.

Below is my code - but it's not printing any number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
	string InputString;
	ifstream fileToOpen;
	fileToOpen.open("input.txt");
        vector <vector <string> > data;

	while(!fileToOpen.eof())
	{
		string line;
		vector<string> tmp;
		size_t pos = string::npos;
		getline(fileToOpen, InputString);
		while ((pos =line.find_first_of(","))!=string::npos)
		{
			tmp.push_back(line.substr(0,pos-1));
			line.erase(0,pos);
		}
		data.push_back(tmp);
	}
	fileToOpen.close();

    for (vector< vector<string> >::size_type u = 0; u < data.size(); u++) {
        for (vector<string>::size_type v = 0; v < data[u].size(); v++) {
            cout << data[u][v] << " ";
        }
        cout << endl;
	}


Not sure if this is an elegant way of doing it. Anyway its not printing the value in console when I run it.
Last edited on
assuming the missing start and end of main() was a paste error, the main error is that you never populated "line":

1
2
getline(fileToOpen, InputString); // populated InputString
while ((pos =line.find_first_of( // line is still empty! 


as for elegance, it's much easier to use getline() to parse the input buffer up to a comma (and of course, never write "while not eof")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector <vector <string> > data;

    ifstream fileToOpen("input.txt");

    for(string line; getline(fileToOpen, line); )
    {
        vector<string> tmp;
        istringstream buf(line);
        for(string word; getline(buf, word, ','); )
        {
            tmp.push_back(word);
        }
        data.push_back(tmp);
    }

    for (vector< vector<string> >::size_type u = 0; u < data.size(); u++) {
        for (vector<string>::size_type v = 0; v < data[u].size(); v++) {
            cout << data[u][v] << " ";
        }
        cout << '\n';
    }
}
Last edited on
Thank you so much. Works Perfectly. I had seen many examples before that uses a while loop checking !eof. But I guess, the way you mentioned is much elegant.

Thank you.Appreciate your help.
Topic archived. No new replies allowed.