第四章 4.1,4.2
来源:互联网 发布:乐知英语在哪里 编辑:程序博客网 时间:2024/04/30 09:48
数组
只有在定义数组时才能使用初始化,此后就不能使用了。
不能将一个数组赋值给另一个数组。
可以使用下标分别给数组的元素赋值。
intcard[4]={3,4,5,6};//okayint hand[4];hand[4]={3,4,5,6};//notallowedhand=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 nameAlistair 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; }
0 0
- 第四章 4.1,4.2
- 第四章 例4.2
- 第四章 例4.1
- 第四章 4.1 基础
- 第四章第四题
- 第四章第四题
- 第四章 4.2节练习
- Vulkan规范:第四章 4.2
- 第四章 内存管理4.1
- Vulkan规范:第四章 4.1
- 第四章
- 第四章
- 第四章
- 第四章
- 第四章
- 第四章
- 第四章
- 第四章
- 安卓手机模拟电脑触摸板
- hdu 1384 Minimum Inversion Number
- 构造函数和This
- SURF算法源码分析
- xib文件关联问题
- 第四章 4.1,4.2
- (LeetCode)Path Sum空指针异常问题
- HEVC代码追踪(六):compressCU
- POJ 3687 Labeling Balls(逆向拓扑)
- 使用awk对文档中特定字段的排序
- 牛人博客和主页---站得高,看得更远(企业大牛的博客)
- hdu 2639 Bone Collector II
- Linux常用系统变量:
- 设计一个结构体bign来存贮高精度非负整数