Menu validation

I am trying to create a calculator program and want to make sure a character is not accepted (e.g g) and the user is asked to input another number. Here is the code i am using inside the SWITCH. How do I make it so the menu will only accept numbers and restart if a number is not entered?

Num1 and num2 are doubles and the cases are char.


case '1' :cout << "Input first number: ";
cin >> num1;


while (!cin);
{

cout << "Input first number: ";
cin >> num1;
cout << "\n";

}

cout << "Input second number: ";
cin >> num2;
cout << "\n";

while (!cin);
{

cout << "Input second number: ";
cin >> num2;

}

cout << fixed << showpoint << setprecision(2);

cout << "--------------------------------\n\n" ;

cout << num1 << " + "<< num2 << " = "<< num1 + num2 << "\n";//Solution

break;
I think if you just remove the semicolons after while () and add cin.clear() and cin.ignore() in your while loops as shown below, it should work. but again i'm not sure

1
2
3
4
5
6
7
8
while (!cin) // remove the semicolon
{
 cin.clear(); //add this statement to clear the error status.
 cin.ignore(256,'\n');
 cout << "Input first number: ";
 cin >> num1;
 cout << "\n";
}
Last edited on
Put the switch inside a while loop, and make sure the switch has a default: case to catch bad input, like in this example :

http://www.cplusplus.com/forum/beginner/104553/2/#msg564228


HTH

Edit: And please always use code tags in the future. Edit your post, select all the code, press the <> button on the right under format menu.

http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
Topic archived. No new replies allowed.