为什么 stringstream ss(s) 与 ss << s 不同?

Den*_*ang 3 c++ string constructor stringstream bidirectional

当我尝试使用 stringstream 时

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string s = "Hello World Test";
    std::stringstream ss(s);

    std::string a, b;
    ss >> a >> b;
    std::cout << a << ' ' << b << std::endl; // Hello World

    ss << " Why Not";
    ss >> a >> b;
    std::cout << a << ' ' << b << std::endl; // Still Hello World

    std::string c, d;
    std::stringstream tt;
    tt << s;

    tt >> c >> d;
    std::cout << c << ' ' << d << std::endl; // Hello World

    tt << " Now Yes";
    tt >> c >> d;  // print Now Yes
    std::cout << c << ' ' << d << std::endl; // Test Now
}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么 stringsteam 构造的行为不同?

我希望 stringstream 可以自由进出。但似乎不是。如果单向使用的话,我没有任何问题。

Chr*_*odd 5

当您从这样的字符串创建字符串流时,默认模式是in|out- 意味着允许输入或输出,但所有指针默认指向缓冲区的开头。因此,当您用它写入字符串流时<<,会覆盖那里的字符串,并且最后的读取将直接从末尾开始。

如果你这样做

std::stringstream ss(s, std::ios_base::in | std::ios_base::out | std::ios_base::ate);
Run Code Online (Sandbox Code Playgroud)

(添加“at the end”标志)它将更像您期望的那样工作,在初始字符串的末尾开始 pptr。

为什么这不是默认值有点神秘(可能只是在标准中编入的最早实现中的一个错误,因为没有人想破坏与此错误功能的向后兼容性)。