gpt4 book ai didi

c++ - 在字符串中使用空字符 (C++)

转载 作者:可可西里 更新时间:2023-11-01 15:41:30 28 4
gpt4 key购买 nike

我正在温习 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;
}

产生输出:

> t
> t
>

幕后发生了什么?为什么字符串字面量和声明的 char 数组在索引 6 处存储了 't'(在内部 '\0' 之后),而声明的字符串却没有?

最佳答案

据我所知,前两个本质上只是一个数组,打印字符串的方式是继续打印,直到遇到\0。因此,在前两个示例中,您从字符串中第 6 个字符的点偏移开始,但在您的情况下,您打印出第 6 个字符,即 t

string 类发生的事情是它将字符串复制到它自己的内部缓冲区中,并通过将字符串从数组的开头复制到第一个 来实现\0 它找到了。因此 t 没有被存储,因为它出现在第一个 \0 之后。

关于c++ - 在字符串中使用空字符 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11582365/

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