Use*_*ame 2 c++ loops std cin do-while
我想提示用户输入一个整数,但是如果用户输入一个非整数,程序应该一直要求一个整数,直到用户符合.
int getInteger(){
int input;
do{
std::cout << "Enter an integer: ";
std::cin >> input;
} while(!(std::cin));
return input;
}
Run Code Online (Sandbox Code Playgroud)
如果用户输入一个整数,该函数将返回它.
但是如果用户输入类似"Hello"的内容,则该函数继续无限,cout"输入一个整数:".
我该如何解决?
!(std::cin)
Run Code Online (Sandbox Code Playgroud)
如果std::cin处于错误状态,例如在输入操作失败后将评估为真.然后,所有后续输入操作将立即失败,而不是更改cin错误状态,因此无限循环.
为了获得你想要的行为,你可以使用类似的东西
while (!(std::cin >> input)) {
std::cout << "Try again\n";
// Clear away the error state
std::cin.clear();
// Ignore what ever garbage is still in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Run Code Online (Sandbox Code Playgroud)
在现实世界中,您可能希望处理(通常不可恢复的)失败eof(有人发送文件结束字符)和bad(cin被破坏,不应该发生)不同于fail无效输入后发生的失败.例如,这是在此参考页面上显示的ignore.但是,这不应该像你的玩具程序那样咬你.