c++ - Have an issue where menu is re-occurring. using switch statement -
i having problem program runs again after runs 1 time. when runs every selection ran correctly no errors never exits program. anyone?
i feel dumb, put while statement repeat itself. ok if take of while statement, else need take off can run it?
#include <iostream> using namespace std; int main() { int in1, in2, in3; char selection; { cout << " welcome cs221 homework 2 menu\n"; cout << " ====================================\n"; cout << " 1. multiply 2 integers\n"; cout << " 2. divide 2 integers\n"; cout << " 3. check if number within range 10-20\n"; cout << " 4. find minimum of list of 3 numbers\n"; cout << "\n"; cout << " 0. exit\n"; cout << " ====================================\n"; cout << " enter selection: "; cin >> selection; cout << endl; switch (selection) { case '1': cout << "please enter 2 integers: "; cin >> in1 >> in2; cout << in1 << " times " << in2 << " " << (in1 * in2) << endl; break; case '2': cout << "please enter 2 integers: "; cin >> in1 >> in2; cout << in1 << " divided " << in2 << " " << ((double) in1 / in2) << endl; break; case '3': cout << "please enter integer: " ; cin >> in1; if ( (in1 >= 10) && (in1 <= 20) ) { cout << in1 << " within range 10-20.\n"; } else { cout << in1 << " not within range of 10-20.\n"; } break; case '4': cout << "please enter 3 integers: "; cin >> in1 >> in2 >> in3; cout << "the minimum "; if( (in1 <= in2) && (in2 <= in3) ) { cout << in1; } else if( (in2 <= in1) && (in2 <=in3) ) { cout << in2; } else { cout << in3; } cout << ".\n"; break; case '0': cout << "goodbye.\n"; default: cout <<selection << "is not valid menu item.\n"; cout << endl; } }while (selection != '0' ); return 0; }
even though works @ ideone, guess if there problem, problem type of selection
, using means reading character character, including newline , all. better choice of type selection
int
, read integers, skipping other characters might inviting problems.
i suggest change type of selection
char
int
, , use 0
,1
, 2
etc, rather '0'
,'1'
, '2'
etc.
by way, forgot use break
in case '0'
:
case 0: //<--- changed '0' 0, assuming selection's type int cout << "goodbye.\n"; break; //add line!
don't forgot change (and in case
statements):
while(selection != 0); //changed '0' 0
Comments
Post a Comment