C++ 数组输出

C++中输出数组数据分两种情况:字符型数组和非字符型数组

当定义变量为字符型数组时,采用cout<<数组名; 系统会将数组当作字符串来输出,如:

1 char str[10]={'1','2'};
2 cout << str <<endl ; //输出12

如果想输出字符数组的地址,则需要进行强制转换,如:

1 char str[10]={'1','2'};
2 cout << static_cast <void *> (str) <<endl ; //按16进制输出str的地址,如:0012FF74

当定义变量为非字符符数组时,采用cout<<数组名; 系统会将数组名当作一个地址来输出,如:

1 int a[10]={1,2,3};
2 cout << a <<endl ; //按16进制输出a的值(地址)    0012FF58

如果需要输出数组中的内容,则需要采用循环,逐个输出数组中的元素,如:

1 int a[10]={1,2,3}; //初始化前三个元素,其余元素为0
2 for( int i=0;i<10;i++ )
3     cout << a[i] <<" " ;
4 cout <<endl ; //输出结果:1 2 3 0 0 0 0 0 0 0

注:for循环的其他用法

1 for (auto i :a)
2     cout<<i<<endl;

原文出处:https://zhidao.baidu.com/question/28706144.html

posted @ 2019-06-26 12:58  ZaneEli  阅读(23591)  评论(0编辑  收藏  举报