break和continue语句
break和continue语句都是程序能够跳过部分代码。可以在switch语句或任何循环中使用break语句,使程序跳到switch或循环后面的语句处执行。continue语句用于循环中,让程序跳过循环体中余下的代码,并开始新一轮循环。
程序6.12
#include<iostream>
const int ArSize = 80;
int main()
{
using namespace std;
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;
}
goto
和C语言一样,C++也有goto语句。下面的语句将跳到使用pairs: 作为标签的位置:
char ch;
cin >> ch;
if (ch == 'P')
goto pairs;
...
pairs: cout << "You've just arrived at Pairs.\n";