C++ Primer Plus 代码学习解析(第六章 6.1-6.3)

文章详细介绍了三个C++代码片段,分别展示了如何使用if、else、while以及条件判断来处理用户输入,控制台输出,包括计数空格、重复输入、数字范围验证等基本功能。
摘要由CSDN通过智能技术生成

6.1 if.cpp

#include <iostream>
int main()
{
    using std::cin;     // using declarations
    using std::cout;
    char ch;
    int spaces = 0;
    int total = 0;
    cin.get(ch);
    while (ch != '.')   // quit at end of sentence
    {
        if (ch == ' ')  // check if ch is a space
            ++spaces;
        ++total;        // done every time
        cin.get(ch);
    }
    cout << spaces << " spaces, " << total;
    cout << " characters total in sentence\n";
    // cin.get();
    // cin.get();
    return 0;
}
  1. 该代码展示了while和if的联合应用
  2. 需要注意的点是使用了cin.get(),字符总数中包括回车键生成的换行符

6.2 ifelse.cpp

#include <iostream>
int main()
{
    char ch;

    std::cout << "Type, and I shall repeat.\n";
    std::cin.get(ch);
    while (ch != '.')
    {
        if (ch == '\n')
            std::cout << ch;     // done if newline
        else
            std::cout << ++ch;   // done otherwise
        std::cin.get(ch);
    }
    // try ch + 1 instead of ++ch for interesting effect
    std::cout << "\nPlease excuse the slight confusion.\n";
    // std::cin.get();
    // std::cin.get();
    return 0;
}
  1. 该代码则对输出成员做了处理,用了if-else进行条件判断
  2. 输入成员如果不是空格,则加一位后输出,如果是回车,则输出回车

6.3 ifelseif.cpp

#include <iostream>
const int Fave = 27;
int main()
{
    using namespace std;
    int n;

    cout << "Enter a number in the range 1-100 to find ";
    cout << "my favorite number: ";
    do
    {
        cin >> n;
        if (n < Fave)
            cout << "Too low -- guess again: ";
        else if (n > Fave)
            cout << "Too high -- guess again: ";
        else
            cout << Fave << " is right!\n";
    } while (n != Fave);
    // cin.get();
    // cin.get();
    return 0;
}
  1. 本代码展现了do-while和if-elseif-else的联合用法
  2. 首先do-while为出口循环,当大于或小于给定值时,输出特定内容
  3. 当等于给定值时,输出“is right”并退出循环

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值