C++学习之分支语句和逻辑运算符(switch语句,break和continue语句)

1.switch语句

switch(integer-expression)
{
    case label1:statement(s)
    case label2:statement(s)
    .......
    default    :statement(s)
}

c++的switch语句就像指路牌,告诉计算机接下来应执行哪行代码。

执行到switch语句时,程序将跳到使用integer-expression的值标记的那一行。integer-expression必须是一个结果为整数的表达式。另外每个标签都必须

是整数常量表达式。如果integer-expression不与任何标签匹配,则程序将跳到标签为default的那一行。

举个小例子:

#include<iostream>

using namespace std;

void shownum();
void report();
void comfort();

int main(void)
{
	shownum();
	int choice;
	cin >> choice;
	while (choice!=5)
	{
		switch (choice)
		{
			case 1: cout << "\a\n";
				break;
			case 2:report();
				break;
			case 3:cout << "The boss was in all day.\n";
				break;
			case 4:comfort();
				break;
			default:cout << "That a not a choice";
		}
		shownum();
		cin >> choice;
	}
	cout << "Bye!\n";
	return 0;
}
void shownum()
{
	cout << "Please enter 1,2,3,4,5:\n"
		"1)alarm                   2)report\n"
		"3)alibi                     4)comfort\n"
		"5)quit\n";
}
void report()
{
	cout << "It's  been an excellent week for buiness.\n";
}
void comfort()
{
	cout << "Your employees think you are the finest\n";
}

然而,switch并不是为处理取值范围而设计的。switch语句中的每一个case都必须是一个单独的整数(包括char),因此switch无法处理浮点测试。

2.break和continue语句

------循环中使用break语句可以使程序跳到switch或循环后面的语句处执行。

------循环中使用continue语句可以使程序跳过循环体余下的代码,并开始新的一轮。

接下来的程序将演示这两条语句是如何工作的。该程序让用户输入一行文本。循环将回显每个字符,如果该字符为句号,则使用break结束循环。接下来程序计算空格数但不计算其他的字符。当字符不为空格时,循环使用continue语句跳过计数部分。

#include<iostream>

using namespace std;
const int ArSize = 80;

int main(void)
{
	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";
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38721302/article/details/82969943