Why setting null in the middle of std string doesn't have any effect

旧街凉风 提交于 2019-12-05 21:52:41

A std::string is not like a usual C string, and can contain embedded NUL characters without problems. However, if you do this you will notice the string is prematurely terminated if you use the .c_str() function to return a const char *.

No - std::strings are not NUL-terminated like C "strings"; the std::string records its length independently.

@Lou is right: don't do that. Instead, do this:

b.erase (3, b.length());

Yes, your expectation is wrong. std::string is meant to be different from C strings (e.g. not necessarily stored in consecutive memory / an array).

To duplicate the first section's behavior, try std::cout << b.c_str() instead of std::cout << b.

I expect std::string will behave identical to char array a.

Why? Nothing in the documentation, anywhere, having to do with std::string says it does this.

My suggestion, stop treating like C++ as C plus some stuff.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!