Search code examples
c++validationuser-inputcin

Input cycle loops twice when given two values


So I just started learning c++ and wanted to make it so you have to enter a number between 1-10, works fine if I run the program.

#include <iostream>
#include <limits>

int main() 
{
    int a;
    do
    {
        std::cout << "Enter a number between 1-10";
        std::cin >> a;
        if (std::cin.fail())  // if input is not an int cin fails
        {
            std::cin.clear(); // this clears the cin
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // this deletes the wrong character
            std::cin >> a;
        }

    } while (a <1 || a >10);
    std::cout << "Your number is " << a <<"";
}

The problem is when you type two values e.g. 15 15. It prints out twice.

Enter a number between 1-10Enter a number between 1-10

Is there a way to remove the space, merging both values into a single number, in order to avoid this behavior? Or is there a better way?

Thanks.


Solution

  • To avoid the repeated input description you just need remove the if statement, and place the buffer clearence and flag reset routine outside:

    int main()
    {
        int a;
        do
        {
            std::cout << "Enter a number between 1-10";
            std::cin >> a;
    
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
        } while (a < 1 || a > 10);
        std::cout << "Your number is " << a << "";
    }
    

    The first value is parsed, all the rest is cleared.

    This has the extra benefit of avoiding an infinite loop when you do input non digit characters which is not addressed with the if statement.