当我请求一个数字但用户输入一个非数字时,如何防止输入循环失控? [英] How do I prevent a runaway input loop when I request a number but the user enters a non-number?

查看:79
本文介绍了当我请求一个数字但用户输入一个非数字时,如何防止输入循环失控?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您输入了错误的类型,我需要知道如何使cin语句看起来不会删除自身。代码在这里:

I need to know how to make my cin statement not appear to 'remove' itself if you input the wrong type. The code is here:

int mathOperator()
{
  using namespace std;

  int Input;
  do
  {
    cout << "Choose: ";
    el();
    cout << "1) Addition";
    el();
    cout << "2) Subtraction";
    el();
    cout << "3) Multiplication";
    el();
    cout << "4) Division";
    el();
    el();
    cin >> Input;

  }
  while (Input != 1 && Input != 2 && Input!=3 && Input!=4);
  return Input;
}

执行,例如输入一个字符,然后循环循环执行

Execute, enter, for example, a character, and it loops nonstop acting as though the cin statement isn't there.

推荐答案

读取错误值后,cin处于失败状态。您必须将其重置。

After reading in a bad value, cin is in a "failed" state. You have to reset this.

必须同时清除错误标志并清空缓冲区。因此:

You must both clear the error flag and empty the buffer. thus:

   cin.clear(); 
   cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

第二次调用冲洗了可能存在的任何数据的输入缓冲区,为您做好准备

The second call "flushes" the input buffer of any data that might be there, to get you ready for the next "cin" call.

如果您发现自己在代码中写了这两行,则可以编写一个简单的内联函数来替换它。

If you find yourself writing these 2 lines "all over your code" you could write a simple inline function to replace it.

   inline void reset( std::istream & is )
   {
       is.clear();
       is.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
   }

尽管我使此功能可以使用任何istream,但大多数情况下会仅用于 cin 用户输入并输入无效内容的地方。如果它是无效的文件或字符串流输入,则无法修复它,而您最好只抛出一个异常。

Although I have made this function take any istream, most of the time it would only be used for cin where a user is entering and enters something invalid. If it's an invalid file or stringstream input, there is no way to fix it and you would do best to just throw an exception.

这篇关于当我请求一个数字但用户输入一个非数字时,如何防止输入循环失控?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆