This seems like a dumb question, but I can't find much info about this.
My code takes user input, and only expects to receive 't'
or 'f'
.
I have a hard time "protecting" the program from edge cases (ex: if the input contains multiple characters and/or spaces, it will loop through every char
in the buffer until it finds 't'
or 'f'
).
I understand that using cin.fail()
only works for an int
. Is there something similar that I could use for a char
? I would like if something along the lines of this worked. I'm just having a hard time figuring out how to define an error/failure of cin
in this case, and how to stop it from looping through the entire buffer.
char choice = '0';
while(choice != 't' && choice != 'f') {
std::cout << "Is this answer true or false? (t/f) ";
std::cin >> choice;
if (error_with_input) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Error. char not entered. Please try again";
}
}
Am I looking at this from the wrong point of view? Should I just make the choice
variable a string
instead of a char
? I could then use getline()
, test if choice
has a length of 1, and if so then finally test if choice
is either 't'
or 'f'
. It seems a little inefficient, but maybe it's a better solution?