【问题标题】:Why does ostringstream strip NULL?为什么 ostringstream 剥离 NULL?
【发布时间】:2011-07-14 07:54:49
【问题描述】:

我有一个字符串,它的最后一部分(后缀)需要多次更改,我需要生成新字符串。我正在尝试使用 ostringstream 来执行此操作,因为我认为,使用流将比字符串连接更快。但是当前一个后缀大于后一个时,它就搞砸了。流也剥离了空字符。

#include<iostream>
#include<sstream>

using namespace std;

int main()
{
  ostringstream os;
  streampos pos;
  os << "Hello ";
  pos = os.tellp();
  os << "Universe";
  os.seekp(pos);
  cout<<  os.str() << endl;
  os << "World\0";
  cout<<  os.str().c_str() << endl;
  return 0;
}

输出

Hello Universe
Hello Worldrse

但我想要Hello World。我该怎么做呢?有没有其他方法可以更快地做到这一点?

编辑: 附加 std::ends 有效。但想知道它在内部是如何工作的。也想知道是否有更快的方法来做同样的事情。

【问题讨论】:

  • 不能确定 stringstream 将是最有效的 - 您应该考虑std::string::replace()的变体之一

标签: c++ string-concatenation ostringstream


【解决方案1】:

字符串“World”已经以空值结尾。这就是 C 字符串的工作原理。 "World\0" 有两个 \0 字符。因此,operator&lt;&lt;(ostream&amp;, const char*) 会将它们一视同仁,并将所有字符复制到\0。如果您尝试os &lt;&lt; "World\0!",您可以更清楚地看到这一点。 ! 根本不会被复制,因为 operator&lt;&lt; 在第一个 \0 处停止。

所以,它不是ostringstream。这就是 C 字符串又名 const char* 的工作原理。

【讨论】:

    【解决方案2】:

    它不会剥离任何东西。 C++ 中的所有字符串文字都由 NUL 终止,因此通过手动插入一个字符串,就任何处理它的人而言,您只需完成字符串。如果您需要这样做,请使用 ostream::writeostream::put — 任何需要 char*(没有额外的大小参数)的东西很可能会特别对待它。

    os.write("World\0", 6);
    

    【讨论】:

      【解决方案3】:

      为什么你认为流操作比字符串快?为什么要在输出到 cout 之前构建字符串?

      如果你想为你的输出添加一个前缀,你可以这样做

      const std::string prefix = "Hello ";
      
      std::cout << prefix << "Universe" << std::endl;
      std::cout << prefix << "World" << std::endl;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        • 2011-07-08
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多