c++ - "if" statement with "or" operator not working -
trying have program make user renter input if choose number isn't 1 2 or 3.
whenever type 1 2 or 3 still wants me re enter integer. did use or operator wrong?
#include <iostream> #include <string> using namespace std; int main() { cout << "choose option 1,2 or 3: \n"; cout << "1: drop single chip 1 slot \n"; cout << "2: drop multiple chips 1 slot \n"; cout << "3: quit program \n"; int choice; cin >> choice; if (choice != 1||2||3) { cout << "please enter 1 2 or 3 \n"; cin >> choice; } else { cout << "it worked \n"; } }
this condition in if statement
if (choice != 1||2||3)
is equivalent to
if ( ( choice != 1 ) || 2 || 3 )
so equal true
because if choice != 1
evaluates false
nevertheless expressions 2
, 3
unequal 0 , consequently each of them evaluate true
.
what mean following
if ( ( choice != 1 ) && ( choice != 2 ) && ( choice != 3 ) )
or write simpler
if ( choice < 1 || choice > 3 )
or maybe 1 more readable
if ( !( 1 <= choice && choice <= 3 ) )
or following way:)
if ( not ( 1 <= choice && choice <= 3 ) )
take account part of program enclose in do-while loop. example
int choice; bool valid_input; { cout << "choose option 1,2 or 3: \n"; cout << "1: drop single chip 1 slot \n"; cout << "2: drop multiple chips 1 slot \n"; cout << "3: quit program \n"; if ( !( cin >> choice ) ) break; valid-input = 1 <= choice && choice <= 3; if ( !valid_input ) { cout << "please enter 1 2 or 3 \n"; } } while ( !valid_input ); if ( valid_input ) { cout << "it worked. there selected option " << choice << std::endl; }
Comments
Post a Comment