gpt4 book ai didi

c++ - 字符串数组长度 C++ 问题?

转载 作者:行者123 更新时间:2023-12-01 15:07:52 25 4
gpt4 key购买 nike

我知道字符串数组以 '\0' 符号结尾。因此,以下代码应打印 0、1、2 和 3。(注意我使用的是基于范围的 for() 循环)。

$ cat app.cpp
#include <iostream>
int main(){
char s[]="0123\0abc";
for(char c: s) std::cerr<<"-->"<<c<<std::endl;
return 0;
}

但它确实打印了整个数组,包括 '\0's。
$ ./app
-->0
-->1
-->2
-->3
-->
-->a
-->b
-->c
-->

$ _

这里发生了什么?为什么不认为字符串以 '\0' 结尾? C++ 集合是否考虑(我想是 C++11)与经典 C++ 不同的字符串?

此外, "0123\0abc" 中的字符数是 8。请注意打印输出为 9 行!

(我知道 std::cout<< 以及 strlen() 以及 for(int i=s; s[i]; i++) 等运行良好,我知道结束终止符,这不是问题!)。

最佳答案

schar [9] 类型,即包含 9 char 的数组s(包括空终止符 char '\0')。 Ranged-based for loop只是对所有 9 个元素的迭代器,空终止符 char '\0'不特别考虑。

Executes a for loop over a range.

Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.


for(char c: s) std::cerr<<"-->"<<c<<std::endl;产生等效于的代码原型(prototype)
{
auto && __range = s ;
auto __begin = __range ; // get the pointer to the beginning of the array
auto __end = __range + __bound ; // get the pointer to the end of the array ( __bound is the number of elements in the array, i.e. 9 )
for ( ; __begin != __end; ++__begin) {
char c = *__begin;
std::cerr<<"-->"<<c<<std::endl;
}
}

关于c++ - 字符串数组长度 C++ 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62338747/

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