Peter Crouch
Peter Crouch

Reputation: 1

Integer Validation in C++

Hello Dear Programmers, I'm coding a system with c++, and I was quite away from this language for a while, I've defined a function in which a set of question will be asked in order to obtain particular data's, Hence inputs are going with validations, and when I want to validate an integer to check that entered value is only numbers, somehow it doesn't work, I wrote a function "isnumber" to check if the value is digit or not, but somehow even when I enter in numbers it goes to my if condition and find as no digit. I hope i'm not making a very stupid mistake, but any consideration is appreciated. here are the codes;

// validation Against Numbers 

bool isNumber(int a)
{
    if (isdigit(a)){

        return true;

    }

    else {

        return false;

    }
}

// Collecting Apartment Details

 cout << "Number Of Bedrooms:" << endl;

    cin >> number_of_bedrooms;

    if (isNumber(number_of_bedrooms) == false ) {

        cout << "Please Do Enter Numbers Only" << endl;
        cin.clear();

    }

    else if (number_of_bedrooms != '2' || number_of_bedrooms != '3' || number_of_bedrooms != '4') {

        cout << "The Number of Bedrooms Is Limited To 2, 3 or 4 !" << endl;
        cin.clear();

    }

Upvotes: 0

Views: 194

Answers (1)

ilent2
ilent2

Reputation: 5241

In C++ you can do away with the isdigit call and instead do something like (untested):

int num;
if (std::cin >> num)
{
    // Read a number from cin
    std::cout << "Yay" << std::endl;
}
else
{
    // Grr
    std::cout << "failed to read number" << std::endl;
    std::cin.clear();  // Clears error state flags
}

The C++ operator << on in streams reads formatted input, so it converts the number you input to an integer, if it fails then it sets the internal error state flags.

If you wan't to use isdigit, you will need to read in a single character (since isdigit takes a single character/int as its argument):

char ch;
std::cin >> ch;
if (std::cin.good() && isdigit(ch))
{
    // Yay
}

It is also a good idea to still check that std::cin is still good even when reading a single character since the call could still fail (perhaps the user sent an EOF signal).

Upvotes: 1

Related Questions