check if cin got the wrong type

#include <iostream>
#include <limits>

int main() {
    int userInput;

    std::cout << "Enter an integer: ";

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

    std::cout << "You entered: " << userInput << std::endl;

    return 0;
}