在从sstream变量中提取字符串后,如何获取剩余的字符串?

dra*_*raw 28 c++

就像我有一个stringstream变量包含"abc gg rrr ff"

当我使用>>stringstream变量时,它给了我"abc".如何获取剩余的字符串:" gg rrr ff"?似乎既不是str()也不行rdbuf().

Naw*_*waz 35

您可以使用std::getline从流中获取其余字符串:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
        stringstream ss("abc gg rrr ff");
        string s1, s2;
        ss >> s1;
        getline(ss, s2); //get rest of the string!
        cout << s1 << endl;
        cout << s2 << endl;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

abc
gg rrr ff
Run Code Online (Sandbox Code Playgroud)

演示:http://www.ideone.com/R4kfV

有一个重载std::getline函数,其中第三个参数采用分隔符,您可以读取该字符串.请参阅以下文档std::getline:

  • 由于字符串可能包含 '\n',`getline(ss, s2, '\0');` 可能更好。 (3认同)
  • @draw(和@Xeo):`std :: getline`尊重流行为.在流行为中,您不能多次读取*same*input.这就是流意味着什么.请在此处查看我的回答以了解详细信息流的含义:http://stackoverflow.com/questions/6010864/why-copying-stringstream-is-not-allowed/6010930#6010930 (2认同)
  • 它的作用是因为它与`std :: getline`在应用于`std :: cout`时的作用相同:从当前流位置开始,读到分隔符(默认为`\n`)或结束时文件. (2认同)

Jna*_*ana 19

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string str("123 abc");
    int a;
    istringstream is(str);
    is >> a;

    // here we extract a copy of the "remainder"
    string rem(is.str().substr(is.tellg()));

    cout << "Remaining: [" << rem << "]\n";
}
Run Code Online (Sandbox Code Playgroud)


seh*_*ehe 9

std::istringstream input;
int extracted;
input >> extracted;
Run Code Online (Sandbox Code Playgroud)

IMO,你可能做的最简单的事情就是:

std::stringstream tmp;
tmp << input.rdbuf();
std::string remainder = tmp.str();
Run Code Online (Sandbox Code Playgroud)

这在性能方面不是最佳的.否则,直接访问stringbuffer(可能使用rbuf().pubseekpostellg在流上...没有测试过).


Che*_*Alf 5

std::getline

 
添加此文本以符合以下SILLYRULE:"正文必须至少30个字符;您输入14"