本文介绍了在向量< string>中存储两个间距字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

考虑这个程序

 #include<bits/stdc++.h>

 using namespace std;

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

此代码存储向量

但问题出在这里.....

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

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

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

但它不会在一行结束处停止,而是将所有单词存储在RS
中,并且FS保持为空

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

请建议一种方法来正确地执行相同的程序

如果你知道更有效的方式,你是欢迎

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

感谢进阶

推荐答案

使用 getline istringstream ,分别为每个句子,然后push_back其中每个单词:

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

换行符('\\\
' getline()的分隔字符

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

这篇关于在向量&lt; string&gt;中存储两个间距字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:45