Given text input of
Car 23 1
Pencil 54 12
Draw
Ball 12
I would like to print into a 2D vector such as:
vector<vector<string>> final_vec = {{Car,23,1},{Pencil,54,12},{Draw},{Ball,12}}
Here is what I have tried so far:
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
using std::cout; using std::endl;
using std::ifstream;
using std::vector;
using std::string;
void read_file(const string &fname) {
ifstream in_file(fname);
string token, line;
vector<string> temp_vec;
vector<vector<string>> final_vec;
while ( getline(in_file, line) ) { //for each line in file
while( in_file >> token ) { //for each element in line
in_file >> token;
temp_vec.push_back(token);
}
final_vec.push_back(temp_vec);
temp_vec.clear();
}
for(vector<string> vec:final_vec) {
for(string ele:vec) {
cout << ele << endl;
}
}
}
int main() {
read_file("text.txt"); //insert your file path here
}
But I am only able to store each individual string element into one vector. How could I take one whole line, split each element into a vector, and then take the whole vector to form a 2D vector?