【问题标题】:C++ stringstream not working correctly after updated with stringstream::str()使用 stringstream::str() 更新后 C++ stringstream 无法正常工作
【发布时间】:2015-02-10 23:16:54
【问题描述】:

我知道stringstream 可以用stringstream::str() 更新,但如果我在此之后在stringstream 中输入其他内容,它就无法按预期工作。下面的 sn -p 演示了这个现象:

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

using namespace std;
int main()
{
    stringstream ss; //ostringstream gives the same output
    ss << "Original string ";
    ss.str("Updated string ");
    ss << "sth else";
    cout << ss.str() << endl;
}

我希望得到输出

Updated string sth else

但它实际上输出

sth elsestring

似乎不是将新输入的字符串附加到当前字符串的末尾(在我的情况下为Updated string),而是尝试从头开始覆盖它。我的代码有什么问题?

Here's a live demo

【问题讨论】:

  • 使用 stringstream 时,您必须处理输入/输出位置和状态 - 避免它并使用 istingstream 或 ostingstream。
  • @DieterLücking 感谢您的建议。我尝试使用 ostringstream,它给出了相同的输出。
  • 另外,不要重复使用它 - 使用新实例,而不是使用 str(....) 操作缓冲区

标签: c++ string stringstream


【解决方案1】:

您需要将std::ios_base::app 添加到openmode。它确保stringstream 对象在每次写入之前寻找到流的末尾。试试这个:

stringstream ss(std::ios_base::app|std::ios_base::in|std::ios_base::out);

【讨论】:

  • @user2079303 值未指定,但行为在27.5.3.1.4 [ios::openmode] 中指定。此外,它适用于ideone。因为你的版本刚刚传入ate
  • @Pradhan 我确实将其从 ios_base::ate 更改为 ios_base::app,但实际上我的错误是忽略了 ios_base::out。也就是说,ios_base::ate(与ios_base::out)应该也可以工作,对吧? (它在 ideone ideone.com/dJxnCk 中确实如此)
  • @user2079303 这很奇怪。我将其解释为寻求结束仅在打开时完成,并且预计 ate 将失败 here。但事实并非如此。 appate 都给出了相同的结果。
  • 根据cppreferencecplusplus ate 应该保证将位置设置为在str(s) 上结束,因为c ++ 11。但我无法从标准本身中找到任何关于此的内容......关于cplusplus 声称除inoutatestringstream c'tor 之外的其他值是impl。已定义,cppreference 没有提及,我也无法从标准中找到任何东西,所以我怀疑它是 bs。
  • @user2079303 它在27.8.2.3 [stringbuf.members]后置条件中。
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多