c++ - 为什么我需要在重用之前清除 stringstream?

标签 c++ stringstream

例如:

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

int main() {
    int num = 10;
    string str;
    stringstream toString;
    toString << num;
    toString >> str;
    cout << str << "\n"; //10

    int num2 = 20;
    string str2;
    toString << num2;
    toString >> str2;
    cout << str2 << "\n"; //str2 is empty
    return 0;
}

我知道我必须像这样清除它:

toString.str("");
toString.clear();

但是为什么在使用operator >>>后没有自动清除呢?

最佳答案

如果我执行 toString >> a >> b >> c 并且第一个失败,我不希望清除标志以便最终状态看起来已经成功。

关于c++ - 为什么我需要在重用之前清除 stringstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27906906/

相关文章:

c++ - 同一个库在16.04下和14.04下定义了不同的符号

delphi - 我需要在 Delphi 中使用子字符串分隔符从 TStringStream 解析字符串?

c++ - 多次提取和插入时奇怪的字符串流行为。

c++ - 我不断收到 'std::invalid_argument' what() : stoi exception thrown for seemingly no reason?

c++ - 使用无分配交换有什么明显的缺点吗?

c++ - 运行时错误 [Ubuntu 15.10 上的 abi :cxx11] when compile with g++-4. 9

c++ - Qt 5 构建错误 : extra characters after test expression

c++ - 嵌套在非特化类中的成员类的特化

c++ - 我可以使用 stringstream 判断 std::string 是否代表数字吗?

c++ - 哪个更高效/整洁 : clearing an existing stringstream or creating a new one?