Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么while(true)在接收到无效输入时跳过cin?_C++_While Loop - Fatal编程技术网

C++ 为什么while(true)在接收到无效输入时跳过cin?

C++ 为什么while(true)在接收到无效输入时跳过cin?,c++,while-loop,C++,While Loop,该while循环在收到错误输入(非整数)后不会等待来自cin的输入。cin是否以某种方式处于错误状态 while (true) { int x {0}; cout << "> "; cin >> x; cout << "= " << x << endl; } while(true){ int x{0}; cout>x; cout一旦cin失败,它将保持无效状态,直到被清除 无参数可用于在意外输入后

该while循环在收到错误输入(非整数)后不会等待来自cin的输入。cin是否以某种方式处于错误状态

while (true) {
    int x {0};
    cout << "> ";
    cin >> x;
    cout << "= " << x << endl;
}
while(true){
int x{0};
cout>x;

cout一旦
cin
失败,它将保持无效状态,直到被清除

无参数可用于在意外输入后取消设置failbit

通过为流错误状态标志指定 默认情况下,分配std::ios_base::goodbit,其效果如下 清除所有错误状态标志的步骤

正如前面指出的,您还必须清除缓冲区

您的示例如下:

while (true) {
  int x{0};
  cout << "> ";
  if (!cin) {
    // unset failbit
    cin.clear();
    // clear the buffer
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
  }
  cin >> x;
  cout << "= " << x << endl;
}
while(true){
int x{0};
cout>x;

cout一旦
cin
失败,它将保持无效状态,直到被清除

无参数可用于在意外输入后取消设置failbit

通过为流错误状态标志指定 默认情况下,分配std::ios_base::goodbit,其效果如下 清除所有错误状态标志的步骤

正如前面指出的,您还必须清除缓冲区

您的示例如下:

while (true) {
  int x{0};
  cout << "> ";
  if (!cin) {
    // unset failbit
    cin.clear();
    // clear the buffer
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
  }
  cin >> x;
  cout << "= " << x << endl;
}
while(true){
int x{0};
cout>x;

实际上这还不够,因为有问题的非整数输入将留在
cin
s缓冲区中,这将导致
cin>>x
立即失败,循环继续,但仍然卡在该输入上。这实际上还不够,因为有问题的非整数输入将留在
cin
s缓冲区中,这将导致
cin>>x
立即失败,循环继续,但仍停留在该输入上。您将受益于此答案您将受益于此答案