Search code examples
c++validationuser-inputiostream

Error with input-validation using std::cin


I have implemented this check in my program to determine if the input is of the right type or not, and if not it asks to re-write the input. If the input is wrong it works just fine but, if the input is right, you need to write it again. How can I avoid this? (you can find an example here https://godbolt.org/z/KjoTbc)

#include <iostream>
#include <limits>

int main() {

int input;
std::cin >> input ;
while (!(std::cin >> input)) { 
std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please, write an integer number\n"; 
};
}

Solution

  • You are not checking the first std::cin >> input ; and running while (!(std::cin >> input)), which asks input, unconditionally.

    Remove the first unchecked reading and try this:

    #include <iostream>
    #include <limits>
    
    int main() {
    
        int input;
        while (!(std::cin >> input)) { 
            std::cin.clear(); 
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Please, write an integer number\n"; 
        }
    }