简体   繁体   English

为什么 ostringstream 会剥离 NULL?

[英]Why does ostringstream strip NULL?

I have a string whose last part(suffix) needs to be changed several times and I need to generate new strings.我有一个字符串,其最后一部分(后缀)需要多次更改,我需要生成新字符串。 I am trying to use ostringstream to do this as I think, using streams will be faster than string concatenations.我正在尝试使用 ostringstream 来执行此操作,因为我认为使用流将比字符串连接更快。 But when the previous suffix is greater than the later one, it gets messed up.但是当前一个后缀大于后一个时,它就搞砸了。 The stream strips off null characters too. stream 也剥离了 null 字符。

#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;
}

Output Output

Hello Universe
Hello Worldrse

But I want Hello World .但我想要Hello World How do I do this?我该怎么做呢? Is there anyother way to do this in a faster manner?有没有其他方法可以更快地做到这一点?

Edit: Appending std::ends works.编辑:附加std::ends有效。 But wondering how it works internally.但想知道它在内部是如何工作的。 Also like to know if there are faster ways to do the same.也想知道是否有更快的方法来做同样的事情。

The string "World" is already null-terminated.字符串“World”已经以空值结尾。 That's how C strings work.这就是 C 字符串的工作原理。 "World\0" has two \0 characters. "World\0" 有两个\0字符。 Therefore, operator<<(ostream&, const char*) will treat them the same, and copy all characters up to \0 .因此, operator<<(ostream&, const char*)将对它们一视同仁,并将所有字符复制到\0 You can see this even more clearly, if you try os << "World\0!"如果您尝试os << "World\0!" ,您可以更清楚地看到这一点。 . . The ! ! will not be copied at all, since operator<< stopped at the first \0 .根本不会被复制,因为operator<<在第一个\0处停止。

So, it's not ostringstream .所以,它不是ostringstream It's how C strings aka const char* work.这就是 C 字符串又名const char*的工作方式。

It doesn't strip anything.它不会剥离任何东西。 All string literals in C++ are terminated by NUL, so by inserting one manually you just finish the string, as far as anyone processing it is concerned. C++ 中的所有字符串文字都由 NUL 终止,因此通过手动插入一个字符串,就任何处理它的人而言,您只需完成字符串。 Use ostream::write or ostream::put , if you need to do that — anything that expects char* (with no additional argument for size) will most likely treat it specially.使用ostream::writeostream::put ,如果你需要这样做 - 任何期望char* (没有额外的大小参数)的东西很可能会特别对待它。

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

Why do you think a stream operation is faster than a string?为什么您认为 stream 操作比字符串快? And why build the string before outputting to cout?为什么要在输出到 cout 之前构建字符串?

If you want a prefix to your output you could just do it like this如果您想要 output 的前缀,您可以这样做

const std::string prefix = "Hello ";

std::cout << prefix << "Universe" << std::endl;
std::cout << prefix << "World" << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM