How can I validate an integer input [duplicate]

You can use getline, find_if_not, and isdigit to check if an entire line is a valid integer or not. This will loop until it reads an integer:

std::string number;
while (std::getline(std::cin, number) && number.end() !=
       std::find_if_not(number.begin(), number.end(), &isdigit))
    std::cout << "gitgud!";

getline will read the input up to the newline, and put it in the string. find_if_not and isdigit will find the first non-digit character. If there are none (meaning it is a valid integer), it will return the end iterator.

Leave a Comment