How to check if the input is a valid integer without any other chars?

后端 未结 7 1961
故里飘歌
故里飘歌 2020-11-28 15:36
#include 
#include 

using namespace std;

int main()
{
    int x;
    cout << \"5 + 4 = \";
    while(!(cin >> x)){
               


        
7条回答
  •  情话喂你
    2020-11-28 15:52

    If you can use C++11 (and your compiler has full regex support), you can also use the library:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string line;
        std::pair value = std::make_pair(0, false);
        std::cout << "5 + 4 = ";
        while (!value.second)
        {
            while (!std::getline(std::cin, line))
            {
                std::cout << "Error, please try again." << std::endl;
                std::cin.clear();
                std::cin.ignore(std::numeric_limits::max(), '\n');
            }
    
            if (!std::regex_match(line, std::regex("(\\+|-)?[[:digit:]]+")))
            {
                std::cout << "Error, please try again." << std::endl;
            }
            else
            {
                value = std::make_pair(std::stol(line), true);
            }
        }
    
        if (value.first == (5 + 4))
        {
            std::cout << "Correct!" << std::endl;
        }
        else
        {
            std::cout << "Incorrect!" << std::endl;
        }
    
        return 0;
    }
    

提交回复
热议问题