How do I validate that the input from the user is a number and nothing else within each case?

``````#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <limits>

using namespace std;

int main ()
{
double operand1, operand2;
double sum, difference, quotient;
int exit = 1;
char choice;

while (exit == 1)
{
cout << "\n\nBASIC CALCULATOR\n"
<< "b. Subtraction\n"
<< "c. Division\n\n"
<< "d. Quit\n\n";

//Get the choice
cout << "Insert Option: ";
cin  >> choice;

//Switch to deal with four cases
switch (choice)
{
case 'a':	cout << "\n\nInput Operands: ";
cin  >> operand1 >> operand2;
sum = operand1 + operand2;
cout << fixed << showpoint << setprecision(2);
cout << "\nThe sum is " << sum << "\n\n";
break;

case 'b':	cout << "\n\nInput Operands: ";
cin  >> operand1 >> operand2;
difference = operand1 - operand2;
cout << fixed << showpoint << setprecision(2);
cout << "\nThe difference is " << difference << "\n\n";
break;

case 'c':	cout << "\n\nInput Operands: ";
cin  >> operand1 >> operand2;
quotient = operand1 / operand2;
cout << fixed << showpoint << setprecision(2);
cout << "\nThe quotient is " << quotient << "\n\n";
break;

case 'd':	exit = 0;
break;

default:    cout << "\nWanring: Input Error!\n\n";

} // exit switch

system("PAUSE");

system("CLS");
} // exit while loop

return 0;
}``````

## All 3 Replies

At line 26

if (choice >= 'd' || choice <= 'a')
{
exit = 0;
cout << "Invalid option, terminating program." << endl;
break;
}

Do you know how to validate if a number entered and nothing else?

You'll have to read the input as a string and test each character to be sure they are digits. If they are, convert the input to a number. This would make a great function. Return the number or -1 if not a number.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.