在c++中如何用cout输出整个字符数组

如题所述

在c++中用cout输出整个字符数组:

char*p="Hello,World!";

cout<<p<<endl;//输出Hello,World!

cout<<*p<<endl;//输出H

cout<<(void*)p<<endl;

cout<<';'<<endl;//输出分号";"

扩展资料

在c++中用cout输出使用:

#include<iostream>

intmain(){

constshortITEMS=5;

intintArray[ITEMS]={1,2,3,4,5};

charcharArray[ITEMS]={'L','M','Y','L','R'};

int*intPointer=intArray;

char*charPointer=charArray;

std::cout<<"整形数组输出"<<"\n";

for(inti=0;i<ITEMS;i++){

std::cout<<*intPointer<<"at"<<intPointer<<"\n";

intPointer++;

}

std::cout<<"字符型数组输出"<<"\n";

for(inti=0;i<ITEMS;i++){

std::cout<<*charPointer<<"at"<<charPointer<<"\n";

charPointer++;

}

return0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-07

可以通过逐个输出字符数组元素的方式进行输出。

如果直接输出数组名,系统默认以字符串方式输出,遇到结束符\0就会停止。要无条件输出字符数组内的所有元素个数,那么只能遍历数组,逐个元素输出。

参考代码如下:

#include <iostream>
using namespace std;
int main()
{
    char buf[5] = {'a', '\0', 'c', 'D', ','};//中间有\0,且最后一个字符并非\0,这种字符数组用cout << buf的方式是无法正确输出的。
    int i;
    for(i = 0; i < 5; i ++)//逐个输出每个元素。
        cout << buf[i];
        
    return 0;
}

第2个回答  2015-09-25
cout<<数组名就可以了,但前提是数组中保存的是字符串,有\0元素。
如不是字符串,就得
for (i=0; i<N; i++) cout<<a[i];
第3个回答  2015-11-09
C++中利用cout的“<<”操作符可以实现字符数组的输出。
例如:
char p[5]="abcd";
cout<<p;
第4个回答  推荐于2017-09-08
例子,
char buf[]="Let's go to the party";
cout<<buf; // printf("%s",buf);本回答被提问者采纳