Ryuzaki Ryuzaki - 1 month ago 8
C++ Question

Storing Two Spaced String in vector<string>

Recently I faced a problem
But before that I will tell you what is the reference

Consider this program

#include<bits/stdc++.h>

using namespace std;

int main()
{
vector<string> RS;
string word;
while(cin>>word)
RS.push_back(word);
}


This code stores each word of spaced string in vector

But the problem comes here .....

#include<bits/stdc++.h>

using namespace std;

int main()
{
vector<string> RS,FS;
string word;

while(cin>>word)
RS.push_back(word);

while(cin>>word)
FS.push_back(word);
}


Here the motive is to store the string words of first line in RS
and of second line in FS vectors

But it doesn't stop at the end of one line and store all words in RS
and FS remains empty.

Please Suggest a way to do the same program correctly
or
If you know more efficient way you are more than Welcome

Thanks in Advance

Answer

Use getline and istringstream, separately for each sentence, and then push_back each word in them:

  string line;
  getline(cin, line);  //Get sentence 1
  istringstream iss1(line);
  while ( iss1 >> word) {    
    RS.push_back(word);
  }
  getline(cin, line);  //Get sentence 2
  istringstream iss2(line);
  while ( iss2 >> word) {    
    FS.push_back(word);
  }

The newline character ('\n') acts as the delimiting character for getline().

Comments