C++ Primer Plus 代码学习解析(第五章 5.13-5.15)

本文档介绍了C++中while,do-while和等待循环的使用示例,包括从用户输入获取数据、条件判断和延迟执行操作,以展示这些控制结构的基本应用。
摘要由CSDN通过智能技术生成

5.13 while.cpp

#include <iostream>
const int ArSize = 20;
int main()
{
    using namespace std;
    char name[ArSize];

    cout << "Your first name, please: ";
    cin >> name;
    cout << "Here is your name, verticalized and ASCIIized:\n";
    int i = 0;                  // start at beginning of string
    while (name[i] != '\0')     // process to end of string
    {
        cout << name[i] << ": " << int(name[i]) << endl;
        i++;                    // don't forget this step
    }
    // cin.get();
    // cin.get();
    return 0;
}
  1. 该代码主要演示了while的用法,与c相同
  2. 入口进行条件判断,符合则进入循环

5.14 waiting.cpp

#include <iostream>
#include <ctime> // describes clock() function, clock_t type
int main()
{
    using namespace std;
    cout << "Enter the delay time, in seconds: ";
    float secs;
    cin >> secs;
    clock_t delay = secs * CLOCKS_PER_SEC;  // convert to clock ticks
    cout << "starting\a\n";
    clock_t start = clock();
    while (clock() - start < delay)        // wait until time elapses
        ;                                   // note the semicolon
    cout << "done \a\n";
    // cin.get();
    // cin.get();
    return 0;
}
  1. 该代码是一段延时循环
  2. 首先定义延时时间,引用头文件ctime
  3. 其中clock_t是时间返回类型的别名,CLOCKS_PER_SEC为符号常量,等于每秒钟包含的系统时间单位数
  4. clock()函数返回值是该程序开始执行后所用的时间

5.15 dowhile.cpp

#include <iostream>
int main()
{
    using namespace std;
    int n;

    cout << "Enter numbers in the range 1-10 to find ";
    cout << "my favorite number\n";
    do
    {
        cin >> n;       // execute body
    } while (n != 7);   // then test
    cout << "Yes, 7 is my favorite.\n";
    // cin.get();
    // cin.get();
    return 0;
}
  1. 该函数展示了dowhile的用法
  2. dowhile为出口循环,先进行循环,当函数体满足条件时,方可跳出循环

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值