4.3 instr1.cpp
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
// cin.get();
return 0;
}
- 该程序作用就是读取来自键盘的输入,储存到数组中,之后再加以显示
- cin使用空白(空格、制表符、换行符)来确定字符串结束的位置,如果输入里需要有空格则该如何呢?请看下一程序
- 如果输入的字符串比设定数组的长度要长的话,则需要进一步探讨
![](https://i-blog.csdnimg.cn/blog_migrate/8ce9abec19a33d5a4d8465b47313cba6.png)
4.4 instr2.cpp
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize); // reads through newline
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
// cin.get();
return 0;
}
- 该代码就利用了cin.getline来读取输入
- cin.getline函数可以用来读取整行,他的结束标志是换行键(回车),因此中间可以加空格
- cin.getline函数有两个参数,第一个是用来储存输入行的数组名称,第二个是要读取的字符数,避免了储存溢出的风险
![](https://i-blog.csdnimg.cn/blog_migrate/14b70f82e46b4ada7fd974203c5d3fdb.png)
4.5 instr3.cpp
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.get(name, ArSize).get(); // read string, newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
// cin.get();
return 0;
}
- 此代码功能相同,只是添加了get()函数
- get()函数是面向行的函数,可以读取换行符,并将其留在队列中(自动添加换行符)
- 本代码采用的是get()函数的一种变体,前面的cin.get()返回一个cin对象,该对象随后用来调用get()函数。
- 总之,get()函数与getline()函数使用方法类似,getline()使用起来更简单一些,get()函数检查错误更简单。
- 之后会有这种拼接特性更详细的解释
![](https://i-blog.csdnimg.cn/blog_migrate/8bb91c16701483e4685bf3a71058031e.png)
4.6 numstr.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "What year was your house built?\n";
int year;
(cin >> year).get();
// cin.get();
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
// cin.get();
return 0;
}
- 原代码通过一种错误的方式展示了cin在读取输入值后遇到回车键则停止读取,但是会将回车留在输入队列中,使下面的cin.getline()读取到回车直接结束。
- 其改正方法可以像上一个代码那样采用cin.get(),读取回车并将其留下来
- 或者采用上述的方式将调用拼接起来,使用get()函数读取并保存回车
![](https://i-blog.csdnimg.cn/blog_migrate/fe4265586e6b74718b73d9d5a7246ec4.png)