Team LiB
Previous Section Next Section

6.7. The while Statement

6.7. while 语句

A while statement repeatedly executes a target statement as long as a condition is true. Its syntactic form is

当条件为真时,while 语句反复执行目标语句。它的语法形式如下:

     while (condition)

The statement (which is often a block) is executed as long as the condition evaluates as true. The condition may not be empty. If the first evaluation of condition yields false, statement is not executed.

只要条件 condition 的值为 true,执行语句 statement(通常是一个块语句)。condition 不能为空。如果第一次求解 condition 就产生 false 值,则不执行 statement

The condition can be an expression or an initialized variable definition:

循环条件 condition 可以是一个表达式,或者是提供初始化的变量定义。

     bool quit = false;
     while (!quit) {                  // expression as condition
         quit = do_something();
     while (int loc = search(name)) { // initialized variable as condition
             // do something

Any variable defined in the condition is visible only within the block associated with the while. On each trip through the loop, the initialized value is converted to bool (Section 5.12.3, p. 182). If the value evaluates as true, the while body is executed. Ordinarily, the condition itself or the loop body must do something to change the value of the expression. Otherwise, the loop might never terminate.

在循环条件中定义的任意变量都只在与 while 关联的块语句中可见。每一次循环都将该变量的初值转换为 bool第 5.12.3 节)。如果求得的值为 true,则执行 while 的循环体。通常,循环条件自身或者在循环体内必须做一些相关操作来改变循环条件表达式的值。否则,循环可能永远不会结束。

Variables defined in the condition are created and destroyed on each trip through the loop.


Using a while Loop

while 循环的使用

We have already seen a number of while loops, but for completeness, here is an example that copies the contents of one array into another:

前面的章节已经用过很多 while 循环,但为更完整地了解该结构,考虑下面将一个数组的内容复制到另一个数组的例子:

     // arr1 is an array of ints
     int *source = arr1;
     size_t sz = sizeof(arr1)/sizeof(*arr1); // number of elements
     int *dest = new int[sz];                // uninitialized elements
     while (source != arr1 + sz)
         *dest++ = *source++; //  copy element and increment pointers

We start by initializing source and dest to point to the first element of their respective arrays. The condition in the while tests whether we've reached the end of the array from which we are copying. If not, we execute the body of the loop. The body contains only a single statement, which copies the element and increments both pointers so that they point to the next element in their corresponding arrays.

首先初始化 sourcedest,并使它们各自指向所关联的数组的第一个元素。while 循环条件判断是否已经到达要复制的数组的末尾。如果没有,继续执行循环。循环体只有单个语句,实现元素的复制,并对两个指针做自增操作,使它们指向对应数组的下一个元素。

As we saw in the "Advice" box on page 164, C++ programmers tend to write terse expressions. The statement in the body of the while

正如 第 5.5. 节提出的关于“简洁即是美”的建议,C++ 程序员应尝试编写简洁的表达式。while 循环体中的语句:

     *dest++ = *source++;

is a classic example. This expression is equivalent to


         *dest = *source; // copy element
         ++dest;  // increment the pointers

The assignment in the while loop represents a very common usage. Because such code is widespread, it is important to study this expression until its meaning is immediately clear.

while 循环内的赋值操作是一种常见的用法。因为这类代码广为流传,所以学习这种表达式非常重要,要一眼就能看出其含义来。

Exercises Section 6.7

Exercise 6.11:

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


     (a) string bufString, word;
         while (cin >> bufString >> word) { /* ... */ }

     (b) while (vector<int>::iterator iter != ivec.end())
         {/*... */ }

     (c) while (ptr = 0)
             ptr = find_a_value();

     (d) while (bool status = find(word))
         { word = get_next_word(); }
         if (!status)
              cout << "Did not find any words\n";

Exercise 6.12:

Write a small program to read a sequence of strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated. For example, if the input is

编写一个小程序,从标准输入读入一系列 string 对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。输出重复次数的最大值,若没有单词重复则输出说明信息。例如,如果输入是:

     how, now now now brown cow cow

the output should indicate that the word "now" occurred three times.


Exercise 6.13:

Explain in detail how the statement in the while loop is executed:

详细解释下面 while 循环中的语句是如何执行的:

     *dest++ = *source++;

Team LiB
Previous Section Next Section