简体   繁体   中英

c++ check if integer variable

User enters date, currently validated to ensure the value is between 1 & 31 inclusive.

However, if they type a non integer value in, it just constantly repeats the error message in an infinite loop.

I have looked around for the answer but everyone else who has asked appears to be far more advanced at c++ than I am, and therefore I don't even understand their initial code.

Here's the code

void Menu::setDate()
{
    date = 0;

    std::cout << "Please enter todays date: (as an integer) ";
    do
    {
        std::cin >> date;   
        if (date > 0 && date < 32)
        {
            break;
        }
        std::cout << "Error: Please enter todays date: (as an integer) ";
    }
    while (true);
 }

The problem is that when a non-digit is entered the stream gets erroneous state. You should clear it and skip invalid input. For example

cin.clear();
cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );

The problem with your code is when an invalid integer is entered, the stream gets error and sets to failbit. Therefore, you need to clear it before you can use I/O operations again. Try this:

void Menu::setDate()
{
    date = 0;

    std::cout << "Please enter todays date: (as an integer) ";

    while(true){
        std::cin >> date;
        if(date > 0 && date < 32){
            break;
        }
        else{
            std::cout << "Error, please enter today's date (as an integer):" << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
 }

Start with checking cin.fail() . This is how you get the infinite loop: when std::cin >> date fails, date is likely to be unchanged. So you have effectively this:

do
{
    if (date > 0 && date < 32)
    {
        break;
    }
    std::cout << "Error: Please enter todays date: (as an integer) ";
}
while (true);

It looks like when std::cin>>a encounters a decimal point it stops taking further input. And the remaining number stays in the input buffer.

int a,b,c;

std::cin>>a;
std::cin>>b;
std::cin>>c;

If the user enters 1.9 , in the first step a becomes 1 and .9 remains in the input buffer. The next std::cin statements skip inputting as the first character in the input buffer is a decimal point. The buffer is cleared when a float input is taken.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM