问题描述
我在 std :: string
..
问题在于,像在类似C的字符串中一样,'\ 0'
被识别为字符串的结尾.
Problem is that '\0'
is being recognized as end of the string as in C-like strings.
例如以下代码:
#include <iostream>
#include <string>
int main ()
{
std::string s ("String!\0 This is a string too!");
std::cout << s.length(); // same result as with s.size()
std::cout << std::endl << s;
return 0;
}
输出以下内容:
7
String!
这是什么问题? std :: string
不应该像对待其他任何字符一样对待'\ 0'
吗?
What is the problem here? Shouldn't std::string
treat '\0'
just as any other character?
推荐答案
考虑一下:如果给您 const char *
,您将如何确定,何为真终止符0,何处为终止符是嵌入一个?
Think about it: if you are given const char*
, how will you detemine, where is a true terminating 0, and where is embedded one?
您需要显式传递字符串的大小,或者从两个迭代器(指针?)构造字符串
You need to either explicitely pass a size of string, or construct string from two iterators (pointers?)
#include <string>
#include <iostream>
int main()
{
auto& str = "String!\0 This is a string too!";
std::string s(std::begin(str), std::end(str));
std::cout << s.size() << '\n' << s << '\n';
}
示例: http://coliru.stacked-crooked.com/a/d42211b7199d458d
编辑:@ Rakete1111让我想起了字符串文字:
Edit: @Rakete1111 reminded me about string literals:
using namespace std::literals::string_literals;
auto str = "String!\0 This is a string too!"s;
这篇关于std :: string停在\ 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!