I'm doing a relatively simple assignment asking us to intake integers and fail gracefully if it hits something that isn't an integer, written in C++. I'm fairly experienced with the language, and I knew it had functionality for checking reading errors in ios::failbit. As a result I'm using cin.fail() to check for errors here, but its running one loop too late--that is, its running the rest of the code first, and not realizing an error happened until the next time it checks the buffer. The obvious solution is to just check twice, but that just causes infinite loops (even if I flush or clear cin.) Is there any way to check more immediately?
Here's my code:
int min = 101; //One higher than the max.
int pile = 0;
int count = 0;
int temp = 0;
int fail;
std::cout << "Input a series of integers between 0 and 100. When you wish to"
" exit, enter -1.\n";
while (true){
std::cin >> temp;
if (std::cin.fail()){
std::cout << "FAILURE: Bad input. It probably wasn't an integer.\n";
std::cout << "Reading will stop.\n";
break;
}
std::cout << "\nTemp is " << temp << "\n";
if (temp > 100 || temp == -1){
break;
}
if (temp < min){
min = temp;
}
pile += temp;
std::cout << "Pile is " << pile << "\n";
count++;
std::cout << "Count " << count << "\n";
}
std::cout << "Your average was: " << (double)pile/count << ".\n";
std::cout << "Your minimum was: " << min << ".\n";
return 0;
}
Aucun commentaire:
Enregistrer un commentaire