C++ Primer Plus 代码学习解析(第四章 4.3-4.6)

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;
}
  1. 该程序作用就是读取来自键盘的输入,储存到数组中,之后再加以显示
  2. cin使用空白(空格、制表符、换行符)来确定字符串结束的位置,如果输入里需要有空格则该如何呢?请看下一程序
  3. 如果输入的字符串比设定数组的长度要长的话,则需要进一步探讨

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; 
}
  1. 该代码就利用了cin.getline来读取输入
  2. cin.getline函数可以用来读取整行,他的结束标志是换行键(回车),因此中间可以加空格
  3. cin.getline函数有两个参数,第一个是用来储存输入行的数组名称,第二个是要读取的字符数,避免了储存溢出的风险

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;
}
  1. 此代码功能相同,只是添加了get()函数
  2. get()函数是面向行的函数,可以读取换行符,并将其留在队列中(自动添加换行符)
  3. 本代码采用的是get()函数的一种变体,前面的cin.get()返回一个cin对象,该对象随后用来调用get()函数。
  4. 总之,get()函数与getline()函数使用方法类似,getline()使用起来更简单一些,get()函数检查错误更简单。
  5. 之后会有这种拼接特性更详细的解释

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;
}
  1. 原代码通过一种错误的方式展示了cin在读取输入值后遇到回车键则停止读取,但是会将回车留在输入队列中,使下面的cin.getline()读取到回车直接结束。
  2. 其改正方法可以像上一个代码那样采用cin.get(),读取回车并将其留下来
  3. 或者采用上述的方式将调用拼接起来,使用get()函数读取并保存回车

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值