gpt4 book ai didi

c++ - 空终止字符数组与字符串对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:57 24 4
gpt4 key购买 nike

我是 C++ 的新手,我正在深入研究 char 数组和字符串对象。我读到 char 数组以字符 '\0' 为空终止,并且字符串对象不为空终止,除非您使用字符串库的成员函数 c_str() .这里我有一些代码,我希望我的第一个循环永远运行,但它们都迭代了大约 6 次。请原谅我糟糕的变量名称,但有人可以向我解释为什么字符串对象不会导致无限循环。

我在想,任何正在索引但尚未分配值的内存位置已经由 char '\0' 表示。如果是这样,请告诉我。

std::string is_terminated = "string";
char is_t[] = "string";

int i = 0;
while (is_terminated[i] != '\0') {
std::printf("Element at index %d is %c\n", i, is_terminated[i]);
i++;
}
std::printf("Times ran: %d\n", i);

int j = 0;
while (is_t[j] != '\0') {
std::printf("Element at index %d is %c\n", j, is_t[j]);
j++;
}
std::printf("Times ran: %d\n", j);

最佳答案

尽管 std::string 不一定存储 '\0'(其实现定义),operator[](size_type pos)如果 pos == size(),则返回空字符。

关于c++ - 空终止字符数组与字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982963/

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