user3657449 user3657449 - 1 year ago 66
C++ Question

Checking if an input is a particular type and in a particular range

I'm trying to test the input a user enters so my program cannot break. The line i'm using is:

while (check != 0){
cout << "Please enter a number 1 - 4 (area of: circle, rectangle, triangle or quit)" << endl;
cin >> response;

if ((isdigit(response)) && ((response >= 1) && (response <= 4))){
check = 0;

cout << "You did not enter a valid digit (1 - 4)" << endl;
check = 1;

} // End of while loop

What i'm trying to do is check if the input is both a digit (integer specifically) and in the range of 1 and 4. For some reason, every value I enter is consider invalid using this method. What should I change or do alternatively to get the desired outcome i'm looking for? (So that it will check if the input is an integer and if that integer is between 1 and 4 (including 1 and 4)).

Answer Source

Assuming response is of type char, you need to use the character constants '1' and '4', not the integer constants 1 and 4.

if ((isdigit(response)) && ((response >= '1') && (response <= '4'))){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download