Try to do the following question;
Write an if statement to do the following: If char variable gender is equal to 'M' or 'm', then display "Male"; if it is equal to 'F' or 'f', then display "Female"; otherwise display "Unknown".
My code is below: but its not doing the right thing Why?
//using the switch statement
#include <iostream>
using namespace std;
int main ( )
string person ;
char gender ;
cout << "Please enter your gender !\n";
cin >> gender;
switch (gender)
{ case 'm':
person = "male" ;
break;
case 'M':
person = "male";
break;
case 'F':
person = "female";
break;
case 'f':
person ="female";
break;
default:
person = "unknown";
}
cout << person << endl;
return 0;
}//switch.cpp
The great thing about switches is they can be used just like if/else statements, and conditionals can easily be just as long.
This would work just the same as the above you posted, because there is no 'break' for 'm' and 'f'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
switch (gender)
{
case'm': ; // ;
case'M':
person = "male";
break;
case'F': ; // ;
case'f':
person ="female";
break;
default:
person = "unknown";
}