数组
只有在定义数组时才能使用初始化,此后就不能使用了。
不能将一个数组赋值给另一个数组。
可以使用下标分别给数组的元素赋值。
intcard[4]={3,4,5,6};//okay int hand[4]; hand[4]={3,4,5,6};//notallowed hand=card;//notallowed
字符串
C-风格字符串
char[8]={‘f’,’a’,’t’,’e’,’s’,’s’,’a’,’\0’};//以空字符结尾’\0’,用来标记字符串的结尾。
字符串常量
char fish[]=”bubbles”; //不必显式的加上空字符
使用字符串常量初始化字符数组的时候通常让编译器计算元素数目。
注意:在确定字符串最短长度时,别忘了把空字符加进去。
字符串常量(双引号)不能与字符常量(单引号)互换。
注意:cin使用空白(空格、制表符、换行符)来确定字符串的结束位置,这意味着cin在获取字符数组时只能读取一个单词。读取该单词后,cin将该字符串放入数组中,并自动在结尾加上空字符。
例
#include<iostream> int main() { using namespace std; const int Arsize =20; char name[Arsize]; char dessert[Arsize]; cout<<"enter your name."<<endl; cin>>name; cout<<"enter your favorite dessert:"<<endl; cin>>dessert; cout<<"i have some delicious "<<dessert<<" for you "<<name<<endl; return 0; }
输出结果是:
Enter your name Alistair dreeb //输入 Enter your favorite dessert: I have some delicious dreeb for you Alistair
面向行的类成员函数:getline()和get()读取一行输入,直到遇到换行符
cin.getline()他通过换行符来确定行尾,但不保存换行符,用空字符替换换行符。
cin.getline(name,20)将一行读入到name数组中,最多只能读取19个,要留一个给空字符。
#include<iostream> int main() { using namespace std; const int Arsize =20; char name[Arsize]; char dessert[Arsize]; cout<<"enter your name."<<endl; cin.getline(name,Arsize); cout<<"enter your favorite dessert:"<<endl; cin.getline(dessert,Arsize); cout<<"i have some delicious "<<dessert<<" for you "<<name<<endl; return 0; }
get()
get()不在读取并丢弃换行符,而是把她留在输入队列中。
假设连续两次调用get()
cin.get(name,arsize); cin.get(dessert,arsize);
由于第一次调用后换行符留在输入队列中,所以第二次调用一开始就遇到换行符,所以实际上他什么也没有读取。
所以可使用不带参数的cin.get()读取下一个字符(包括换行符)
cin.get(name,arsize); cin.get(); cin.get(dessert,arsize);
另一种方式是cin.get(name,arsize).get();
#include<iostream> int main() { using namespace std; const int Arsize =20; char name[Arsize]; char dessert[Arsize]; cout<<"enter your name."<<endl; cin.get(name,Arsize).get(); cout<<"enter your favorite dessert:"<<endl; cin.get(dessert,Arsize).get(); cout<<"i have some delicious "<<dessert<<" for you "<<name<<endl; return 0; }