如果用户输入了<第一次尝试60。我想确保没有字母输入,因此进行输入验证,但也要小于某个数字。如果用户输入60,我如何让它对第一个输入进行操作?
int score;
cout << "Enter your test score: ";
cin >> score;
while (!(cin >> score)){
cin.clear();
cin.ignore(100, 'n');
cout << "Please enter valid number for the score. ";
}
while (score < 60){
cout << "You failed try again. ";
cin >> score;
}
您可以将两个条件的逻辑组合成一个循环:
int score;
std::cout << "Enter your test score: ";
// check if either extracting score failed or if score is less than 60:
while(!(std::cin >> score) || score < 60) {
if(std::cin) { // extraction succeeded but `score` was less than 60
std::cout << "You failed try again. ";
} else { // extraction failed
// you may want to deal with end of file too:
//if(std::cin.eof()) throw std::runtime_error("...");
std::cout << "Please enter valid number for the score. ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
}