How to store data from text file into vector of vector

Hi. I'm c++ beginner. Currently, I still learn how to store data into vector from text file. I don't know I do it right or wrong. But it seem wrong because nothing appear when I want to display the solution.

I hope anyone here can teach me :)
Thank you.

My text file.
11 12 13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28
29 30 31 32 33

I have unequal size of row here.

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
34
35
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;

int main() 
{
	string line;
	ifstream myfile("example.txt");
	vector<vector<int>> vect;
	if (myfile.is_open())
	{
		while (getline(myfile, line))
		{
			//cout << line << '\n';
			for (int i = 0; i < vect.size(); i++)
			{
				for (int j = 0; j < vect[i].size(); j++)
				{
					myfile >> vect[i][j];
					cout << setw(4) << vect[i][j];
				}
				cout << endl;
			}
		}
		myfile.close();
	}

	else cout << "Unable to open file";

	return 0;
}
Multiple mistakes here.
Your vector of vectors is totally empty, so it's size is 0, so your loops will not loop.
Also, you are reading a line from the file and then you are trying to read ints from it. You need to read a line and then read the ints from the line.

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 <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::ifstream fin("input.txt");
    if (!fin)
    {
        std::cerr << "Can't open input file\n";
        return 1;
    }

    std::vector<std::vector<int>> vect;

    for (std::string line; std::getline(fin, line); )
    {
        vect.push_back(std::vector<int>());
        std::istringstream iss(line);
        for (int n; iss >> n; )
            vect.back().push_back(n);
    }
    
    for (const auto& v: vect)
    {
        for (int n: v)
            std::cout << std::setw(3) << n << ' ';
        std::cout << '\n';
    }
}

> for (int i = 0; i < vect.size(); i++)
Your vector has no size when you start, so nothing happens.
You need to read a line and then read the ints from the line.


Oh I got it. No wonder, the solution wont display.
Btw, thank you Dutch for your explanation and help.

Have a nice day ahead :)

can someone help me with this?
[cpp.sh/3g4da][/code]
Topic archived. No new replies allowed.