我尝试以两种方式在字符串中添加空终止符(\0)。
一种是使用'\0',另一种是使用"\0",而且在这两种情况下,我得到了不同的输出结果:
我正在获取输出
有人可以解释一下为什么字符串将
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string test1 = "";
test1 += "\0";
cout << test1.size() << endl;
string test2 = "";
test2 += '\0';
cout << test2.size() << endl;
}
我正在获取输出
0
1
有人可以解释一下为什么字符串将
'\0'
作为字符而不是空终止符吗?如果我打印test1
或test2
,它会打印一个空字符串。
'\0'
)是一个"字符字面量",另一个("\0"
)是一个"字符串字面量"。 - undefined'\0'
)。而 C 风格的字符串是以空字符结尾的,所以"\0"
表示一个长度为零的空字符串。 - undefinedstd::string
可以通过std::string
的length
或size
成员函数知道自己的长度,不需要任何空终止符。你似乎对C风格的字符串感到困惑,因为在C风格的字符串中,空终止符是必需的。 - undefined”\0”
是一个包含两个字符的字符串字面量,都是'\0'
。一个空字符串只是””
;它只包含一个字符,即'\0'
。 - undefined