gpt4 book ai didi

c++ - 为什么在 std 字符串中间设置 null 没有任何效果

转载 作者:太空狗 更新时间:2023-10-29 19:42:32 24 4
gpt4 key购买 nike

考虑

#include <string>
#include <iostream>

int main()
{
/*
hello
5
hel
3
*/
char a[] = "hello";
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;
a[3] = 0;
std::cout << a << std::endl;
std::cout << strlen(a) << std::endl;

/*
hello
5
hel o
5
*/
std::string b = "hello";
std::cout << b << std::endl;
std::cout << b.length() << std::endl;
b[3] = 0;
std::cout << b << std::endl;
std::cout << b.length() << std::endl;

getchar();

}

我希望 std::string 的行为与 char 数组 a 相同。就是这样,在字符串中间插入空字符,将“终止”字符串。然而,事实并非如此。我的期望错了吗?

最佳答案

std::string 不像通常的 C 字符串,可以毫无问题地包含嵌入的 NUL 字符。但是,如果您这样做,您会注意到如果您使用 .c_str() 函数返回 const char *,则字符串会提前终止。

关于c++ - 为什么在 std 字符串中间设置 null 没有任何效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4653745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com