I am having a hard time accepting the users input if they enter something < 60 on the first try. I want to make sure no letters are inputing hence the input validation but also less then a certain number. If the user enters 60 how can I get it to act on the first input?
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;
}
CodePudding user response:
You can combine the logic of both your conditions into a single loop:
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');
}
}