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

问题描述 投票:0回答:1

当我尝试使用 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
}

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

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

c++ string constructor stringstream bidirectional
1个回答
2
投票

当您从这样的字符串创建字符串流时,默认模式是

in|out
——意味着允许输入或输出,但所有指针默认指向缓冲区的开头。因此,当您使用
<<
写入字符串流时,它会覆盖那里的字符串,并且您在末尾的读取将直接超出末尾。

如果你这样做

std::stringstream ss(s, std::ios_base::in | std::ios_base::out | std::ios_base::ate);

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

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

© www.soinside.com 2019 - 2024. All rights reserved.