While loop with conditions

Hello,

I've already did a couple searches on the forum but wasn't able to find a particular solution to my problem. The first while loop in my code should only be used when the letter entered is not equal to m or f but unfortunately the while loop runs even when m or f are entered and the program does not pass this point.

But when I run the while loops when it says while (!(friend_sex=='m') || (friend_sex=='f')) then the code somehow works for m but of course not for f. Also, when I delete one of the conditions, it works for the condition left.

Can anyone point out where the error is?

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "std_lib_facilities.h"
int main ()
{
string first_name;
cout<<"Enter the name of the person you want to write to\n";
cin>>first_name;
cout<<"Dear "<<first_name<< ", \n"<< "wie geht's dir? Ich vermisse dich.";
string friend_name;
cout<<" What's your best friends name?\n";
cin>>friend_name;
cout<<"Hast du irgenwann "<<friend_name<<" gesehen?\n";
char friend_sex;
cout<<"Click m or f if your friend is male or female\n";
cin>>friend_sex;
        while (!(friend_sex=='m') || !(friend_sex=='f')) {
        cout<<"You have pressed an incorrect character. Please try again.\n";
        cin>>friend_sex;
}
if (friend_sex=='m')
                cout<<"If you see "<<friend_name<<" please tell him to call me.\n";
else if (friend_sex=='f')
                cout<<"if you see "<<friend_name<<" please tell her to call me.\n";
int age;
cout<<"How old are you?\n";
cin>>age;
while ((age<0) || (age>110)){
        cout<<"you're kidding me! Try again.\n";
        cin>>age;
}
cout<<"I heard you just had a birthday and are "<<age<<" years old.\n";
if (age==12)
        cout<<"Next year you'll be "<<++age<<"\n";
else if (age==17)
        cout<<"Next year you can vote.\n";
else if (age==70)
        cout<<"I hope you're having a nice retirement!\n";
cout<<"Yours sincerely,\n"<<"\n";
cout<<first_name<<"\n";
}

while ( !(friend_sex=='m') && !(friend_sex=='f') ) {

Or, simpler: while ( (friend_sex!='m') && (friend_sex!='f') ) {

Hi JLBorges,

thanks for the response. It worked but just out of curiosity, why wouldn't || work? E.g. when I enter " f ", then the first condition would be true and the second would be false so it should also work?
> why wouldn't || work?
> when I enter " f ", then the first condition would be true and the second would be false so it should also work?

true || false is true; so the while loop continues to execute.
Just wrote out a truth table and it makes sense now. || would make the while statement true even if one was true, leading the while statement to always run.
Yep! Exactly. Thanks for the help!
Topic archived. No new replies allowed.