C++ to check if user input is a number, not a character or a symbol

后端 未结 2 880

I have been trying to incorporate a check to see if the input from the user is a valid input. For example my program wants the user to guess a number between 1-1000. My prog

2条回答
  •  甜味超标
    2020-12-10 10:03

    Here's a snippet I like to keep around for using in these sorts of situations.

    int validInput()
    {
        int x;
        std::cin >> x;
        while(std::cin.fail())
        {
            std::cin.clear();
            std::cin.ignore(std:numeric_limits::max(),'\n');
            std::cout << "Bad entry.  Enter a NUMBER: ";
            std::cin >> x;
        }
        return x;
    }
    

    Then any place you want to use cin>>guess, instead, use guess = validInput();

提交回复
热议问题