c++ check if integer variable

c++, integer, loops, validation

Solution

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');
        }
    }
 }

Problem

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); } ```

Original source