c++ - 字符串数组长度 C++ 问题?
问题描述
我知道字符串数组以 '\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++)
,等等,我知道结束终止符,这不是问题!)。
解决方案
s
是 类型char [9]
,即包含 9 s 的数组char
(包括空终止符 char '\0')。基于范围的 for 循环仅对所有 9 个元素进行迭代,空终止符 char'\0'
不被特别考虑。
在一个范围内执行 for 循环。
用作对一系列值(例如容器中的所有元素)进行操作的传统 for 循环的更易读等价物。
for(char c: s) std::cerr<<"-->"<<c<<std::endl;
产生等效于的代码原型
{
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;
}
}
推荐阅读
- python - 为什么即使条件为假,它也会打印“欢呼”?
- excel - 使用DTPicker2控件的Excel表格移到Win10后在单机上坏了
- perl - 无法理解 perl 中的命令
- python - 将用户输入存储在列表中,以 %d 格式提供
- django - 将文件发送到具有 FileField 的 Django REST 端点
- sql - 需要添加子查询或其他内容以从重复行中获取记录?
- python - Docker 构建挂起
- spring-boot - 使用非主复合键的 OneToMany 关系
- html - 如何制作一个的底部边缘低于背景图像
- excel - 保存在 G 盘目录时出现 PathFile 访问错误