C++中输出数组

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

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

char str[10]={'1','2'};

cout << str <<endl ; //输出12

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

char str[10]={'1','2'};

cout << static_cast <void *> (str) <<endl ; //按16进制输出str的地址,如:0x6afef2

static_cast 类型转换,void *是空指针类型

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

int a[10]={1,2,3};

cout << a <<endl ; //按16进制输出a的值(地址)    0012FF58

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

 

int a[10]={1,2,3}; //初始化前三个元素,其余元素为0

for( int i=0;i<10;i++ )

    cout << a[i] <<" " ;

cout <<endl ; //输出结果:1 2 3 0 0 0 0 0 0 0

转自:https://zhidao.baidu.com/question/28706144.html

  • 17
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++输入输出数组的方法有多种。以下是几种常用的方法: 1. 使用循环遍历数组,逐个输入输出数组元素。 ```cpp #include <iostream> using namespace std; int main() { int arr[3]; // 输入数组元素 for(int i=0; i<3; i++) { cin >> arr[i]; } // 输出数组元素 for(int i=0; i<3; i++) { cout << arr[i] << " "; } return 0; } ``` 2. 使用指针或迭代器遍历数组,逐个输入输出数组元素。 ```cpp #include <iostream> using namespace std; int main() { int arr[3]; int *p = arr; // 输入数组元素 for(int i=0; i<3; i++) { cin >> *(p+i); } // 输出数组元素 for(int i=0; i<3; i++) { cout << *(p+i) << " "; } return 0; } ``` ```cpp #include <iostream> #include <vector> using namespace std; int main() { vector<int> arr(3); vector<int>::iterator it; // 输入数组元素 for(it=arr.begin(); it!=arr.end(); it++) { cin >> *it; } // 输出数组元素 for(it=arr.begin(); it!=arr.end(); it++) { cout << *it << " "; } return 0; } ``` 3. 使用数组指针作为函数参数,直接传递数组地址和长度,实现输入输出数组。 ```cpp #include <iostream> using namespace std; void input(int *arr, int len) { for(int i=0; i<len; i++) { cin >> *(arr+i); } } void output(int *arr, int len) { for(int i=0; i<len; i++) { cout << *(arr+i) << " "; } } int main() { int arr[3]; // 输入数组元素 input(arr, 3); // 输出数组元素 output(arr, 3); return 0; } ``` 以上是几种常用的输入输出数组的方法,可以根据实际情况选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值