1. 程式人生 > >C++學習之分支語句和邏輯運算子(switch語句,break和continue語句)

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;
}