当我们有多个条件要检查时,我们使用这种形式的if-else。
在此程序中:我们将检查输入的字符是否为有效的字母?
1)检查字母的条件
(ch>='a'&& ch<='z') || (ch>='A' && ch<='Z')
字符大于或等于“ a”(小写)且小于或等于“ z”(小写),或字符大于或等于“ A”(大写)且小于或等于“ Z”(大写) )。
2)检查数字的条件
(ch>='0' && ch<='9')
字符大于或等于'0'且小于或等于'9'。
看程序:
#include<iostream> using namespace std; int main(){ char ch; //输入一个字符 cout<<"Enter a character: "; cin>>ch; //验证字符的条件是字母 if( (ch>='a'&& ch<='z') || (ch>='A' && ch<='Z')) { cout<<"Entered character is an alphabet"; } //验证字符的条件是数字 else if(ch>='0' && ch<='9') { cout<<"Entered character is a digit"; } //其他字符无效字符 else { cout<<"Enter a valid character"; } cout<<endl; return 0; }
输出结果
First run: Enter a character: W Entered character is an alphabet Second run: Enter a character: i Entered character is an alphabet Third run: Enter a character: 7 Entered character is a digit Fourth run: Enter a character: + Enter a valid character