Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to "safely" use cin with a char

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').

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading