赞
踩
break和continue语句都使程序能够跳过部分代码。可以在switch语句或任何循环中使用break语句,使程序跳到switch或循环后面的语句处执行。continue语句用于循环中,让程序跳过循环体中余下的代码,并开始新一轮循环(参见图6.4)。
程序清单6.12演示了这两条语句是如何工作的。
- //6.12
- /*该程序让用户输入一行文本。循环将回显每个字符,如果该字符为句点,则使用break结束循环。
- 这表明,可以在某种条件为true时,使用break来结束循环。
- 接下来,程序计算空格数,但不计算其他字符。当字符不为空格时,循环使用continue语句跳过计数部分。
- */
- #if 1
- #include<iostream>
- using namespace std;
- const int ArSize = 80;
-
- int main()
- {
- char line[ArSize];
- int spaces = 0;
-
- cout << "Enter a line of text:\n";
- cin.get(line, ArSize);
- cout << "Complete line: \n" << line << endl;
- cout << "Line through first period:\n";
- for (int i = 0; line[i] != '\0'; i++)
- {
- cout << line[i];
- if (line[i] == '.')
- break;
- if (line[i] != ' ')
- continue;
- spaces++;
- }
- cout << "\n" << spaces << " spaces\n";
- cout << "Done.\n";
-
- system("pause");
- return 0;
- }
- #endif

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。