-1

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?

Dracep
  • 388
  • 2
  • 13
  • 1
    Possible duplicate of [How do I iterate over the words of a string?](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string) – Jay Nov 04 '18 at 02:05
  • Should be `while ( in_file >> token1 >> token2 >> token3 )`. – David G Nov 04 '18 at 02:06
  • @0x499602D2 Thank you for your input, but what if token2 or token3 are empty? Should they all go to in_file? – Dracep Nov 04 '18 at 02:13
  • Then do `while ( getline(in_file, line) )` to get the line, put the line into a stringstream, do `while ( ss >> token )` to iterate over each token in the line. – David G Nov 04 '18 at 02:25
  • @0x499602D2 This was helpful! I have tried to make an edit to my code, but somehow I am still not getting every element of each line? – Dracep Nov 04 '18 at 02:35
  • @user4581301 I thought I had it at that time, but I still couldn't figure out how to work with the in_file and token. After doing research into it for an hour, I couldn't find any implementations. If you can, please show how I can use while ( ss >> token )? – Dracep Nov 04 '18 at 02:39
  • Shoot. When the question vanished I thought you had it. – user4581301 Nov 04 '18 at 04:32

1 Answers1

1

You have the basic structure, you just need to create the stringstream and use that for the extraction:

while (getline(in_file, line)) {
  stringstream ss(line);
  vector<string> temp_vec;
  string str;
  while (ss >> str) {
    temp_vec.push_back(str);
  }
  final_vec.push_back(temp_vec);
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • Flawless! I wasn't sure how to integrate the stringstream into my loop, and now I learned how to make a 2D vector out of a text file. Thanks a ton! – Dracep Nov 04 '18 at 02:57