I was doing a project for an online course and the final project was to make a Build Your Adventure program where the user has choices and they lead to endings. I deleted the huge intro and just now copied the part where I have the first choice. So basically, it all works when I don't write valid numbers, but when I write in a letter... the whole program begins an infinite loop. Please help: Here is the code:
#include <iostream>
int main() {
int c1;
std::cout << "After what felt like thirty minutes of "
"walking you reached a wall. Yes, a wall.\n"
"A wall so tall and wide you couldn't imagine "
"climbing over it or walking around it.\n";
std::cout << "Luckly, you see two animals willing to help you.\n"
"1) A mole that can build a tunnel under the wall\n"
"2) An eagle that can carry you over the wall\n";
std::cout << "Enter 1 or 2 to make a choice: ";
std::cin >> c1;
while (!(std::cin >> c1) || c) {
std::cout << "Error! Please enter a valid input!\n";
std::cout << "Enter 1 or 2 to make a choice: ";
std::cin >> c1;
std::cout << "\n"
}
When you input invalid inputs for int
, the stream goes into failed state and can't read further inputs. So you have to clear the error state of the stream and ignore anything left in the input stream.
#include <iostream>
#include <limits>
int main() {
int c1;
while (true)
{
std::cout << "Enter 1 or 2 to make a choice: ";
if ((std::cin >> c1) && (c1 == 1 || c1 == 2)) break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Error! Please enter a valid input!\n";
}
// Now c1 is either 1 or 2
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.