Team LiB
Previous Section Next Section

6.9. The do while Statement

6.9. do while 语句

We might want to write a program that interactively performs some calculation for its user. As a simple example, we might want to do sums for the user: Our program prompts the user for a pair of numbers and produces their sum. Having generated one sum, we'd like the program to give the user the option to repeat the process and generate another.

在实际应用中,可能会要求程序员编写一个交互程序,为用户实现某种计算。一个简单的例子是:程序提示用户输入两个数,然后输出读入数之和。在输出和值后,程序可以让用户选择是否重复这个过程计算下一个和。

The body of this program is pretty easy. We'll need to write a prompt, then read a pair of values and print the sum of the values we read. After we print the sum, we'll ask the user whether to continue.

程序的实现相当简单。只需输出一个提示,接着读入两个数,然后输出读入数之和。输出结果后,询问用户是否继续。

The hard part is deciding on a control structure. The problem is that we want to execute the loop until the user asks to exit. In particular, we want to do a sum even on the first iteration. The do while loop does exactly what we need. It guarantees that its body is always executed at least once. The syntactic form is as follows:

关键在于控制结构的选择。问题是要到用户要求退出时,才中止循环的执行。尤其是,在第一次循环时就要求一次和。do while 循环正好满足这样的需要。它保证循环体至少执行一次。

     do
             statement
     while   (condition);

Unlike a while statement, a do-while statement always ends with a semicolon.

while 语句不同。do-while 语句总是以分号结束。



The statement in a do is executed before condition is evaluated. The condition cannot be empty. If condition evaluates as false, then the loop terminates; otherwise, the loop is repeated. Using a do while, we can write our program:

在求解 condition 之前,先执行了 do 里面的 statementcondition 不能为空。如果 condition 的值为假,则循环结束,否则循环重复执行。使用 do while 循环,可以编写程序如下:

     // repeatedly ask user for pair of numbers to sum
     string rsp; // used in the condition; can't be defined inside the do
     do {
        cout << "please enter two values: ";
        int val1, val2;
        cin  >> val1 >> val2;
        cout << "The sum of " << val1 << " and " << val2
             << " = " << val1 + val2 << "\n\n"
             << "More? [yes][no] ";
        cin  >> rsp;
     } while (!rsp.empty() && rsp[0] != 'n');

The body of this loop is similar to others we've written and so should be easy to follow. What might be a bit surprising is that we defined rsp before the do rather than defining it inside the loop. Had we defined rsp inside the do, then rsp would go out of scope at the close curly brace before the while. Any variable referenced inside the condition must exist before the do statement itself.

循环体与之前编写的其他循环语句相似,因此很容易理解。奇怪的是此代码把 rsp 定义在 do 之前而不是在循环体内部。如果把 rsp 定义在 do 内部,那么 rsp 的作用域就被限制在 while 前的右花括号之前了。任何在循环条件中引用变量都必须在 do 语句之前就已经存在。

Because the condition is not evaluated until after the statement or block is executed, the do while loop does not allow variable definitions:

因为要到循环语句或者语句块执行之后,才求解循环条件,因此 do while 循环不可以采用如下方式定义变量:

     // error: declaration statement within do condition is not supported
     do {
         // ...
         mumble(foo);
     } while (int foo = get_foo()); // error: declaration in do condition

If we could define variables in the condition, then any use of the variable would happen before the variable was defined!

如果可以在循环条件中定义变量的话,则对变量的任何使用都将发生在变量定义之前!

Exercises Section 6.9

Exercise 6.17:

Explain each of the following loops. Correct any problems you detect.

解释下列的循环。更正你发现的问题。

     (a) do
              int v1, v2;
              cout << "Please enter two numbers to sum:" ;
              cin >> v1 >> v2;
              if (cin)
                  cout << "Sum is: "
                       << v1 + v2 << endl;
         while (cin);

     (b) do {
             // ...
         } while (int ival = get_response());

     (c) do {
             int ival = get_response();
             if (ival == some_value())
                  break;
         } while (ival);
          if (!ival)
              // ...

Exercise 6.18:

Write a small program that requests two strings from the user and reports which string is lexicographically less than the other (that is, comes before the other alphabetically). Continue to solicit the user until the user requests to quit. Use the string type, the string less-than operator, and a do while loop.

编写一个小程序,由用户输入两个 string 对象,然后报告哪个 string 对象按字母排列次序而言比较小(也就是说,哪个的字典序靠前)。继续要求用户输入,直到用户请求退出为止。请使用 string 类型、string 类型的小于操作符以及 do while 循环实现。


Team LiB
Previous Section Next Section