在向量<string>中存储两个间隔字符串

时间:2016-10-22 16:24:22

标签: c++ string vector cin

最近我遇到了一个问题 但在此之前,我会告诉你什么是参考

考虑这个程序

 #include<bits/stdc++.h>

 using namespace std;

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

此代码将间隔字符串中的每个单词存储在向量

但问题来了.......

 #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);
 }

这里的动机是在RS中存储第一行的字符串字 和FS向量中的第二行

但它不会停在一行的末尾并将所有单词存储在RS中 和FS仍然是空的。

请建议正确执行相同程序的方法 要么 如果您知道更有效的方式,那么您不仅仅是欢迎

先谢谢

1 个答案:

答案 0 :(得分:5)

分别对每个句子使用getlineistringstream,然后按下其中的每个单词:

  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);
  }

换行符('\ n')充当getline()分隔符