3

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

Ryuzaki
  • 95
  • 1
  • 9
  • [avoid `bits/stdc++.h`](http://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c) – asu Oct 22 '16 at 16:40
  • Sure But Is the reason more compiling time or not using it will help me learn the header files and their respective use ? – Ryuzaki Oct 23 '16 at 18:35
  • it is not standard and leads to inconsistent behavior between compilers. plus, yes, it does increase compile time. – asu Oct 23 '16 at 18:39
  • Thank you Sir I will keep it mind – Ryuzaki Oct 26 '16 at 17:25

1 Answers1

5

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().

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79