C ++输入验证:如何仅接受某些整数

时间:2018-03-20 23:31:20

标签: c++ validation input

我希望用户输入1,2,3或4,并且只输入这些数字。 我不想要:5,79,4rf,1XXXXX,2!,abc 1234等。

如果我使用'cin>> ',然后它会切断输入'2'之类的东西。到2并离开'!'在下一个输入中,所以getline()更可取。我列出的代码在技术上有效,但是当我在用户输入无效输入后再次询问另一个输入时,会留下额外的输入行。

感谢您的帮助。

bool check = true;
string input;
int choice;

cout << "Please enter 1, 2, 3, or 4:" << endl;
getline(cin, input);

do
{
  check = true;
  if (input.length() != 1 || !isdigit(input[0]))
  {
     cout << "error, enter a valid input" << endl;
     check = false;
     cin.clear();
     cin.ignore(INT_MAX, '\n');
     getline(cin, input);
  }
  else
  {
     choice = stoi(input);
     if (!(choice == 1 || choice == 2 || choice == 3 || choice == 4))
     {
        cout << "error, enter a valid input" << endl;
        check = false;
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        getline(cin, input);
     }
     else
     {
        check = true;
     }
  }

} while (check == false);

1 个答案:

答案 0 :(得分:0)

getline(cin, input);消耗整行或失败,getline上的cin失败几乎是cin的结尾。如果你有数据,你就得到了整条线。 cin.ignore(INT_MAX, '\n');无法忽略任何内容,因此用户最终必须再次按Enter才能进入getline(cin, input);重试。

保持基本的限制,我会把它清理成更像

的东西
bool check = false; // assume failure
string input;
int choice;

cout << "Please enter 1, 2, 3, or 4:" << endl;

while (!check)
{
    if (getline(cin, input)) // test that we got something
    {
        if (input.length() != 1 || !isdigit(input[0]))
        {
            cout << "error, enter a valid input" << endl;
            // don't need to do anything else here
        }
        else
        {
            choice = input[0] - '0'; // easier conversion
            if (!(choice == 1 || choice == 2 || choice == 3 || choice == 4))
            {
                cout << "error, enter a valid input" << endl;
                // don't need to do anything else here
            }
            else
            {
                check = true; // all done
            }
        }
    }
    else
    {
        // to be honest there isn't much you can do here. You can clear and 
        // ignore, but it's hard to make unformatted input fail and still 
        // have a viable console. Maybe you should throw an exception, but 
        // for a simple program I'm all for giving up. 
        cerr << "Aaaaaaahhhhrrrg!\n";
        exit(-1);
    }

} 

我假设失败,因为我只有一个地方需要设置check标志:成功!这样可以更轻松地选择此代码并将其放入函数中,以便您可以更轻松地重用它。使循环永久化并将check = true;替换为return choice;