0

while loop runs forever when a character is entered by user instead of an integer. How to stop it?

Here's my program #include<iostream> #include<stdlib.h>//for system pause int wish,i; float x,y,z; using namespace std; int main() { while(true) { cout<<"\n\n Hello User what is your wish today\n\n"; cout<<" For Basic Maths enter 1\n\n"; cout<<" to exit enter 2\n\n"; cin>>wish; cout<<"\nyou choose "<<wish<<endl; if (wish==2) { cout<<"\n\n\n BYE BYE\n\n\n"; break; } switch (wish) { case 1: cout<<"\n\n\nFor addition enter 1\n\n"<< "for subtraction enter 2\n\n"<< "for multiplication enter 3\n\n"<< "for division enter 4\n\n"<< "to return to previous menu 5\n\n"; cin>>i; cout<<"\nYour Choice: "<<i; switch (i){ case 1: cout<<"\n\nEnter first number: ";cin>>x; cout<<"\nEnter second number: ";cin>>y; cout<<"\nresult is: "<<x+y; break; case 2: cout<<"\n\nEnter first number: ";cin>>x; cout<<"\nEnter second number: ";cin>>y; cout<<"\nresult is: "<<x-y; break; case 3: cout<<"\n\nEnter first number: ";cin>>x; cout<<"\nEnter second number: ";cin>>y; cout<<"\nresult is: "<<x*y; break; case 4: cout<<"\n\nEnter first number: ";cin>>x; cout<<"\nEnter second number: ";cin>>y; cout<<"\nresult is: "<<x/y; break; case 5: break; default : cout<<" which is Not Available"; } break; default : cout<<" which is Not Available"; } } system("pause"); }

10th Aug 2016, 4:08 PM
Preet
Preet - avatar
1 Answer
+ 1
You could always do if (wish != 1) wish = 2; After cin >> wish If wish isn't 1, it would set wish to 2. Even if the user types in 2, which isn't 1, it's only going to set wish to 2 anyway, the exact same value. And since wish is 2 at this point, it's going to end the program because of the if statement that you have afterwards 😁
10th Aug 2016, 4:25 PM
Cohen Creber
Cohen Creber - avatar