Search code examples
c++validationstdin

CIN within certain range


I am trying to make a cin where the user can only enter 0 to 1. If the user doesnt enter those numbers then he should get an error saying "Please enter within the range of 0 to 1."

But its not working.

What am i doing wrong?

   int alphaval = -1;
    do
    {
        std::cout << "Enter Alpha between [0, 1]:  ";
        while (!(std::cin >> alphaval)) // while the input is invalid
        {
            std::cin.clear(); // clear the fail bit
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid entry
            std::cout << "Invalid Entry!  Please Enter a valid value:  ";
        }
    }
    while (0 > alphaval || 1 < alphaval);

    Alpha = alphaval;

Solution

  • Try this:

    int alphaval;
    cout << "Enter a number between 0 and 1: ";
    cin >> alphaval;
    while (alphaval < 0 || alphaval > 1)
    {
            cout << "Invalid entry! Please enter a valid value: ";
            cin >> alphaval;
    }