尝试验证数据时内部有些奇怪

Something strange inside while when try to validate data

我正在尝试使用 while 循环来验证数据!当得到错误的数据时应该再次询问。但是当错误的数据得到程序时,跳过 cin >> a;

再次循环

这是我已经尝试过的两个验证码:

第一个[Pic of console]

int a;

do
{
  a = NULL;
  cout << "Press some number: ";       
  cin >> a;

} while (a>=0 || a<=0);

第二个:[Pic of console]

int a;

do
{
  cin.clear();    cin.sync();

  cout << "give me number: ";   cin >> a;

} while (cin.fail());

这样你可以检查输入的是不是数字:

int a;
bool flag=false;
while (true)
{
    flag=false;
    std::string input;
    std::cout << "Press some number: ";
    std::getline(std::cin,input);
    try
    {
        a = stoi(input);
    }
    catch(const std::exception& e)
    {
        std::cout <<"Invalid number" << std::endl;
        flag=true;
    }
    if (!flag)
        break;

还有其他方法可以做到这一点,但我不会用向量或其他东西来扰乱你的头脑。