16.1、if语句
当C++程序必须决定是否执行某个操作时,通常使用if语句来实现选择。if有两种格式:if和if else。
if语句的语法与while相似:
if(text-condition)
statement
如果text-condition(测试条件)为true,则程序执行statement(语句)。后者可以是一条语句,或者语句块。如果测试条件为false,则程序将跳过语句。与循环测试一样,if测试条件也将被强制转换为bool值,因此0将被转换为false,非零为true。
#include<iostream>
int main()
{
using namespace std;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence ";
return 0;
}
仅当ch为空格时,语句++spaces;才会被执行。因为语句++total;位于if语句的外面,因此在每轮循环中都将被执行。注意:字符总数中包括按回车键生成的换行符。
16.2、if else语句
if语句让程序决定是否执行特定的语句或语句块,而if else语句则让程序决定执行两条语句或语句块中的哪一条,这种语句对于选择其中一种操作很有用。if else语句的通用格式如下:
if (text-condition)
statement1
else
statement2
如果测试条件为true或非0,则程序将执行statement1,跳过statement2;如果测试条件为false或0,则程序跳过statement1,执行statement2。
#include <iostream>
int main()
{
using namespace std;
char ch;
cout << "Type,and I shall repeart." << endl;
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
cout << ch;
else
cout << ++ch;
cin.get(ch);
}
cout << endl << "Please excuse the slight confusion." << endl;