为什么我在while while语句中得到无限循环?

zie*_* ny 2 c++ algorithm data-structures

在我看来,如果输入不是整数,循环将启动,并等待用户的下一个输入.但是,下面的代码循环使用"value for a",并且用户无法输入其他输入.

#include<iostream>

using namespace std;

int main()
{
        int a;
        do{
                cout <<"Value for a: ";
                cin >>a;
        }
        while(cin.fail());
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

当用户输入错误输入时,设置错误状态cin.cin在清除错误状态之前,您无法读取任何内容.

你不得不:

  1. 调用cin.clear()以清除错误状态,并且
  2. 打电话cin.ingore()忽略其余部分.

你需要的东西是:

do {
   cout <<"Value for a: ";
   if ( cin >> a )
   {
      // Input was successful.
      break;
   }

   // Clear the error state of the input stream.
   cin.clear();

   // Ignore the rest of the line.
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (true);
Run Code Online (Sandbox Code Playgroud)

并添加

#include <limits>
Run Code Online (Sandbox Code Playgroud)

能够使用 std::numeric_limits