目錄
一、if語句
二、if else語句
三、格式化if else語句
四、if else if else結構
一、if語句
if語句讓程序能夠決定是否應執行特定的語句。
if有兩種格式:if和if else。
if語句的語法與while相似:
if(test-condition)statement;
如果test-condition(測試條件)為true,則程序將執行statement(語句),后者既可以是一條語句,也可以是語句塊。如果測試條件為false,則程序將跳過語句。和循環測試條件一樣,if測試條件也將被強制轉換為bool值,因此0將被轉換為false,非零為true。整個if語句被視為一條語句。
例如,假設讀者希望程序計算輸入中的空格數和字符總數,則可以在while循環中使用cin.get(char)來讀取字符,然后使用if語句識別空格字符并計算其總數。程序清單6.1完成了這項工作,它使用句點(.)來確定句子的結尾。
//if
#if 1
#include<iostream>
using namespace std;int main()
{char ch;int spaces = 0;int total = 0;cin.get(ch);//成員函數cin.get(char)讀取輸入中的下一個字符(即使它是空格),并將其賦給變量chwhile (ch != '.'){if (ch == ' ')spaces++;total++;cin.get(ch);}cout << spaces << " spaces, " << total << " characters total in sentence\n";//字符總數中包括按回車鍵生成的換行符system("pause");return 0;
}
#endif
二、if else語句
if語句讓程序決定是否執行特定的語句或語句塊,而if else語句則讓程序決定執行兩條語句或語句塊中的哪一條,這種語句對于選擇其中一種操作很有用。
if else語句的通用格式如下:
if(test-condition)statement1
elsestatement2
如果測試條件為true或非零,則程序將執行statement1,跳過statement2;如果測試條件為false或0,則程序將跳過statement1,執行statement2。
從語法上看,整個if else結構被視為一條語句。
例如,假設要通過對字母進行加密編碼來修改輸入的文本(換行符不變)。這樣,每個輸入行都被轉換為一行輸出,且長度不變。這意味著程序對換行符采用一種操作,而對其他字符采用另一種操作。正如程序清單6.2所表明的,該程序還演示了限定符std::,這是編譯指令using的替代品之一。
//if else
#if 1
#include<iostream>int main()
{char ch;std::cout << "Type, and I shall repeat.\n";std::cin.get(ch);//成員函數cin.get(char)讀取輸入中的下一個字符(即使它是空格),并將其賦給變量chwhile (ch != '.'){if (ch == '\n')std::cout << ch;elsestd::cout << ++ch;//ASCII碼std::cin.get(ch);}std::cout << "\nPlease excuse the slight confusion.\n";system("pause");return 0;
}
#endif
運行情況:
?
三、格式化if else語句
if else中的兩種操作都必須是一條語句。如果需要多條語句,則需要用大括號將它們括起來,組成一個塊語句。
四、if else if else結構
程序清單6.3使用這種格式創建了一個小型測驗程序。
#if 1
#include<iostream>
using namespace std;
const int Fave = 27;int main()
{int n;cout << "Enter a number in the range 1-100 to find";cout << "my favorite number: ";do{cin >> n;if (n < Fave)cout << "Too low -- guess again: ";else if (n > Fave)cout << "Too high -- guess again: ";elsecout << Fave << " is right!\n";} while (n != Fave);system("pause");return 0;
}
#endif