Reputation: 101
I am trying to read in lines of standard input and put each string on a line (separated by a space) into an index of a vector of vector strings, and then put each line in a separate index, but I'm confused how i would do this with getline.
Example, say my stdin is:
Hello
I want a
sand wich
The vector of string vectors would look like:
0: {"Hello"}
1: {"I", "want", "a"}
2: {"sand", "wich"}
I'm trying to code something like this:
vector <vector <string> > name;
string line, s;
int count= -1;
while(getline(cin, line, '\n'))
{
count++;
while (getline(line, s, ' '))
{
name[count].push_back(s);
}
}
Would this do what I am trying to do?
Oh so with a string stream, like this?
vector <vector <string> > name;
string line, string;
stringstream ss;
int count= -1;
while(getline(cin, line, '\n'))
{
count++;
ss.str(line);
while (ss >> string)
{
name[count].push_back(string);
}
ss.clear();
}
Upvotes: 0
Views: 5450
Reputation: 1381
You can try the following code .
vector <vector <string> > name;
vector<string> tmp;
string line, str;//It should not be string
stringstream ss;
int count= -1;//no need for count variable as pushing to a vector starts from 0
while(getline(cin, line, '\n'))
{
count++;
ss.str(line);
while(ss >> str)
{
tmp.push_back(str);//extracting tokens of string in tmp vector
}
name.push_back(tmp);//pushing vector of string to main vector
tmp.clear();
ss.clear();
}
Upvotes: 1