首页 > 解决方案 > 字符串数组长度 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++),等等,我知道结束终止符,这不是问题!)。

标签: c++arraysstringc++11

解决方案


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;
  }
}

推荐阅读