Loop until integer input is in required range fails to work with non-digit character inputs

后端 未结 4 1329
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 17:25

I\'m having a problem with what should be incredibly simple code. I want to take in an integer between 1 and 3 with error checking. It works fine for checking for numbers

4条回答
  •  时光取名叫无心
    2020-12-01 18:18

    #include 
    #include 
    
    using namespace std;
    
    int validatedInput(int min = 1, int max = 3)
    {
        while(true)
        {
            cout << "Enter a number: ";
            string s;
            getline(cin,s);
            char *endp = 0;
            int ret = strtol(s.c_str(),&endp,10);
            if(endp!=s.c_str() && !*endp && ret >= min && ret <= max)
                return ret;
            cout << "Invalid input. Allowed range: " << min << "-" << max <

提交回复
热议问题