C++如何在不破坏程序的情况下输入用户值

May*_*ron 1 c++ types input cin

我试图从用户获得一个整数,但如果他们输入"ckefkfek",它将导致程序垃圾邮件和破坏.我也希望他们输入一个浮点数,但我得到了同样的问题,并没有线索如何检查这个.

int option = 0;
while (option != 3)
{
    cout << "Enter 1, 2, or 3: ";
    cin >> option;
    switch (option)
    {
        case 1:
            cout << "Enter a float: ";
            float myfloat;
            cin >> myfloat;
            myFunc(myfloat); // must be a float for this function to work.
            break;
        case 2:
            // do stuff
            break;
        case 3:
            // do stuff
            break;
        default:
            cout << endl << "Not a valid option." << endl;
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果没有不断的错误,我该怎么做?谢谢!

Jon*_*ely 5

bool input_ok = false;
while (!input_ok)
{
  cout << "Enter 1, 2, or 3: ";
  if (cin >> option)
  {
    input_ok = true;
    ...
  }
  else
  {
    cout << "Stop being silly\n";
    std::string dummy;
    if (cin >> dummy)
      cin.clear();
    else
      throw std::runtime_error("OK, I'm not playing any more");
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上,如果输入可能失败,您需要测试它是否失败.你可以通过检查流的状态来检查它,从中读取cin >> option; if (cin) ...,或者通过组合读取和测试,如下所示:if (cin >> option) ...

如果输入失败,请读取无法解析为整数的任何内容并将其丢弃,然后重试.