我的cin在while循环中被忽略 [英] My cin is being ignored inside a while loop
问题描述
我试图在我的第一个C ++程序中编写一个简单的问题和数字检查器。
问题是,当我输入一个类似一两个或三个的字符串时,程序会变成无限循环,它会忽略cin函数,将生命重新分配给一个数字。
I am trying to code a simple question and number checker into my first C++ program. Problem is, when I type a string like one two, or three, the program becomes and infinite loop and it ignores the cin function to re-assign lives to a number.
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
while(lives != 1 && lives != 2 && lives != 3 && !isdigit(lives))
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
以下是我当前的代码及您的建议:
Here is my current code with your suggestions:
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
std::cin.ignore();
std::cin.clear();
if (std::cin >> lives)
{
while(lives != 1 && lives != 2 && lives != 3)
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
}
推荐答案
#include <iostream>
#include <limits>
int main()
{
int lives = 0;
std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
while(!(std::cin >> lives) || lives < 1 || lives > 3)
{
std::cout << "You need to input a number, not words." << std::endl;
std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0;
}
好吧。 std :: cin.clear();
负责重置失败位。 std :: cin.ignore
删除流中留下的任何错误输入。我已经调整停止条件。 ( isDigit
是一个冗余检查,如果生活在1和3之间,那么显然它是一个数字)。
Alright. std::cin.clear();
takes care of resetting the fail bits. std::cin.ignore
removes any wrong input left in the stream. And I've adjusted the stop condition. (isDigit
was a redundant check, if lives is between 1 and 3 then clearly it's a digit).
这篇关于我的cin在while循环中被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!