1 C风格字符串
char类型数组,输出数组名不是输出一个地址,而是输出数组内字符组成字符串。
数组长度比字符数多1,如下例。但可以使用char a[] = “happy”,a表示6元素数组。
int main()
{
char a[5] = {'h', 'a', 'p', 'p', 'y'};
cout << a << endl;
return 0;
}
输出结果:happy烫烫烫藺锡`跟
int main()
{
char a[6] = {'h', 'a', 'p', 'p', 'y'};
cout << a << endl;
char b[] = "happy"; a和b是同等的
cout << b; 输出happy
return 0;
}
输出结果:happy
#include <typeinfo>
#include <iostream>
using namespace std;
int main()
{
char a[6] = {'h', 'a', 'p', 'p', 'y'};
char* ptr = a;
cout << typeid(ptr).name() << endl; //输出char *
cout << ptr << endl; //输出happy,a/ptr的作用是把该地址对应的字符
// 及其以后的字符组成字符串输出,a/ptr初始都指向第一个字符
//故输出输出happy
cout << ptr + 1 << endl; // 输出appy,ptr此时指向'a', 输出'a'即'a'之后字符组成的字符串
cout << a + 2 << endl; //输出ppy,同理,
cout << *ptr << endl; // 输出h,ptr指向首地址
cout << *(ptr + 1) << endl; // 输出a
cout << *ptr + 1 << endl; //输出105,*ptr = 'h',ASCII对应104
cout << 'i' + 2 << endl; //输出107
return 0;
}
2 string 类
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210603232917777.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210603232946948.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
3 getline函数
getline(cin, s2) 以换行符为字符串结束的标志
getline(cin, s2, ‘,’) 以,为字符串结束的标志
getline函数才能读入空格
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (int i = 0; i < 2; i++) {
string city, state;
getline(cin, city, ',');
getline(cin, state);
cout << city << " " << state << endl;
}
return 0;
std::cout << "Hello World!\n";
}