对于常规C字符串,空字符'\0'表示数据的结尾.
那么std::string,我可以使用嵌入空字符的字符串吗?
我正在刷我的C++,偶然发现了一个关于字符串,字符数组和空字符('\0')的奇怪行为.以下代码:
#include <iostream>
using namespace std;
int main() {
cout << "hello\0there"[6] << endl;
char word [] = "hello\0there";
cout << word[6] << endl;
string word2 = "hello\0there";
cout << word2[6] << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产生输出:
> t
> t
>
Run Code Online (Sandbox Code Playgroud)
幕后发生了什么?为什么字符串文字和声明的char数组存储't'at索引6(在内部之后'\0'),但声明的字符串不存在?