0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Grant
  • 431
  • 3
  • 8

1 Answers1

2

Reading the input as a std::string, or at least as a char[], is the right way to go. Validate the input after you have read it in, not while you are reading it, eg:

string choice;
do {
    std::cout << "Is this answer true or false? (t/f) ";
    std::cin >> choice;
    
    if (choice != "t" && choice != "f") {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Error. char not entered. Please try again";
    }
    else {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        break;
    }
}
while (true);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • thanks so much! just out of curiosity, but what is the reason for calling the `ignore` function in the else (success) block – Grant Apr 04 '23 at 04:42
  • @Grant to ensure there is no lingering `\n` in the buffer before your next input. You didn't show your other code, so it's unknown if that `\n` might cause any issues for you, such as this one: https://stackoverflow.com/questions/21567291/ – Remy Lebeau Apr 04 '23 at 06:15