If Else Only Yields One Option
Mar 15, 2018 at 4:18pm UTC
Hi all, new to C++. This is a snippet from a decision tree homework assignment using if else statements. The goal is to create a tree that a pilot would use in an emergency (not for real emergency use!). My problem is that all input only yields the last if else option, "Please enter y or n." I've tried to troubleshoot through searching and referencing my text, no luck. Thank you in advance for your eagle eyes.
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
int engFail()
{
char choice;
cout << "Are you airborne? \n" ;
cin >> choice;
choice = islower(choice);
if (choice == 'y' )
{
elec();
}
else if (choice == 'n' )
{
cout << "Have a drink and call a mechanic." << endl;
mainMenu();
}
else if (choice != 'y' || 'n' )
{
cout << "Please enter y or n." << endl;
}
return 0;
}
Mar 15, 2018 at 4:23pm UTC
(choice != 'y' || 'n' )
This is always true.
On the left,
choice != 'y' . Sometimes true, sometimes false.
On the right,
'n' . Always true. Always. No comparison being made, nothing to do with choice. Just
'n' , on its own.
I've tried to troubleshoot through searching and referencing my text, no luck
Reading a textbook is a pretty bad way to try to troubleshoot a program. In fact, it's an awful way. The best way is to debug the actual program.
What does this do?
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
int engFail()
{
char choice;
cout << "Are you airborne? \n" ;
cin >> choice;
cout << "User entered: " << choice << '\n' ;
choice = islower(choice);
cout << "choice transformed to: " << choice << '\n' ;
if (choice == 'y' )
{
cout << "Entered choice == y " << '\n' ;
elec();
}
else if (choice == 'n' )
{
cout << "Entered choice == n " << '\n' ;
cout << "Have a drink and call a mechanic." << endl;
mainMenu();
}
else if (choice != 'y' || 'n' ) // this line is wrong
{
cout << "Entered choice == y || n " << '\n' ;
cout << "Please enter y or n." << endl;
}
return 0;
}
Last edited on Mar 15, 2018 at 4:26pm UTC
Mar 15, 2018 at 4:25pm UTC
I guess you want to lower(...).
Line 19: The if statement doesn't work this way. Change to:
else if (choice != 'y' || choice != 'n' )
You can omit this if because it is already determined that it is neither 'y' nor 'n'.
Mar 15, 2018 at 7:00pm UTC
Thank you both so much. I made the changes suggested by coder777 and the statement functions perfectly now. Repeater I really appreciate the reminder to step through my own code.
Topic archived. No new replies allowed.