【问题标题】:C++ input validation: how to accept only certain intsC++ 输入验证:如何只接受某些整数
【发布时间】:2025-11-30 02:20:02
【问题描述】:

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

如果我使用'cin >>',那么它会切断输入到类似'2!'到 2 并离开 '!' in 用于下一个输入,因此 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);

【问题讨论】:

  • 不相关的choice = stoi(input); 在这里有点矫枉过正。你知道你只有一个字符,它是一个数字,所以你可以用choice = input[0] - '0';

标签: c++ validation input


【解决方案1】:

getline(cin, input); 消耗整行或失败,getlinecin 上的失败几乎是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;

【讨论】: