Storing Two Spaced String in vector<string>

风流意气都作罢 提交于 2019-12-07 13:02:41

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/40194396/storing-two-spaced-string-in-vectorstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!