而当输入错误的输入时,循环无限循环 [英] while loop loops infinitely when wrong input is entered

查看:136
本文介绍了而当输入错误的输入时,循环无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当输入错误的输入时,以下循环会无限循环?如何更正?

Why does the following loop infinitely when a wrong input is entered? How do I correct this?

int operation;
    while (true) {
        cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. ";
        cin >> operation;
        if (operation >= 1 && operation <= 5) break;
        cout << "Please enter a number from 1 to 5, inclusive.\n";
    }


推荐答案

遇到错误输入流,流将处于故障状态。你明确地必须清除该流上的故障位,然后清空它。尝试:

After an error is encountered on the input stream, the stream will be in a failure state. You explicitly have to clear the failure bits on that stream and empty it afterwards. Try:

#include <limits> 
#include <iostream>

...
...
// erroneous input occurs here

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

您可以检查输入是否通过检查good(),bad ),fail()或eof()。这些函数只返回内部状态位的状态(即如果相应的位被设置为true,除了good(),很明显,如果一切顺序都会返回true)。

You can check if the input raised an error by checking the return value of good(), bad(), fail() or eof(). These functions just return the state of the internal status bits (i.e. true if the according bit is set - except for good(), obviously, which will return true if everything is in order).

这篇关于而当输入错误的输入时,循环无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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