• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

easy quick question - validation

Hello Experts,

Can somebody explain me on beginner level how should I rewrite this code? I'm trying to do validation for char variable with while loop.

do {
cout << "Please enter your sex\n";
cout << "\t M - Male\n";
cout << "\t F - Female\n";
cout << " ==> ";
cin >> s;
} while ( s != 'f' );

this works but just for 'f' but when I add "or"

do {
cout << "Please enter your sex\n";
cout << "\t M - Male\n";
cout << "\t F - Female\n";
cout << " ==> ";
cin >> s;
} while ( s != 'f' || s != 'F' || s != 'm' || s != 'M');

thanks

0
Luxana
Asked:
Luxana
3 Solutions
 
AlexFMCommented:
while (  ! (s == 'f' || s == 'F' || s == 'm' || s == 'M') );
0
 
zzrayCommented:
what is also equivalent to the above ans is  while (  s != 'f' && s != 'F' && s != 'm' && s != 'M' );
i.e replacing all your ors with ands.

The reson why your condition did not work is because you are saying that if
s is not 'f' or s is not 'F'or sis not 'm or s is not 'M' continue  looping.. but s can only take on one value 'f' or 'F' 'm' or 'M' so if its any of the four or none of the four vaues the expression evaluates to 1 and remains in the loop.




0
 
r_a_j_e_s_hCommented:
simply change the || to && .....

while ( s!='f' && s!='F' && s!='m' && s!='M')
0
 
r_a_j_e_s_hCommented:
it will work till the entered text is not equal to any one of the character
0
 
LuxanaAuthor Commented:
thanks you all

I'll accept zzray answer because of his explanation and rest of answers assist.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now