while 也是一种入口条件循环,只有测试条件和循环体:

  1. while (/* 测试条件 */ ) {
  2. //循环体
  3. }

5.2.1 for 与 while

本质上这两个循环是相同的。以下代码等价:

  1. //以下等价
  2. for (int i = 0; i < 5; ++i) {
  3. cout << i << endl;
  4. }
  5. int i = 0;
  6. while (i < 5) {
  7. cout << i << endl;
  8. ++i;
  9. }
  10. //以下也等价
  11. while (i < 0) {
  12. cout << i << endl;
  13. }
  14. for (; i < 0) {
  15. cout << i << endl;
  16. }

通常,知道循环次数的用 for,无法预知循环次数的用 while。

5.2.2 编写延时循环

这时就得用系统时钟来完成。clock() 函数返回程序开始执行后所用的系统时间。

但是,返回时间的单位不一定是秒,类型有的系统是 long,有的是 unsigned long。头文件 ctime(较早的是 time.h)解决了这个问题。它定义了一个符号常量 CLOCKS_PER_SEC,表示每秒钟包含的系统时间单位数。另外,ctime 将 clock_t 作为 clock() 返回类型的别名,编译器会将它转换成合适的类型。

示例:

  1. #include <iostream>
  2. #include <ctime>
  3. using namespace std;
  4. int main()
  5. {
  6. cout << "Enter the delay time, in seconds:";
  7. float secs;
  8. cin >> secs;
  9. clock_t delay = secs * CLOCKS_PER_SEC;
  10. clock_t start = clock();
  11. while (clock() - start < delay) {
  12. //...
  13. }
  14. cout << done << endl;
  15. return 0;
  16. }

类型别名 C++ 为类型建立别名的两种方式:

  • 使用预处理器:#define BYTE char。BYTE 是别名。
  • 使用 typedef 关键字:typedef char BYTE。BYTE 是别名。

推荐使用第二种,typedef 不会创建新类型,只是为已有类型建立一个新名字。