cin.ignore(); cin.clear();

When doing a cin >> operation with a char variable like this.
1
2
3
4
 char controlChar; 
 cout << "Would you like to make another choice?";
 cout << "Enter 'y', or 'n' : ";
 cin >> controlChar;


If the user enters more than one character it causes problems. If you use a loop to help control the input error you get something like this.

Would you like to make another choice?
Enter 'y', or 'n' : sd
Enter 'y', or 'n' :
Enter 'y', or 'n' :_


What can be done to separate the input? Would a get function work to only get the first character of the input? Can you cin.ignore(); everything but the first character?

Thanks,
Dave
if I had no choice but to input with char I would cin.ignore(1000, '\n'); ignores 1000 characters until it encounters a newline
Last edited on
you can always make it like this:

1
2
3
4
5
string in;
cin >> in;

if ( in.c_str()[0] == 'y' || in.c_str()[0] == 'Y')
//something 
Last edited on
Yanson +1

 
#include <limits> 
1
2
cin >> controlChar;  // get first character of line input
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );  // ignore everything else on line 

Hope this helps.
I've used this before, I guess I was thinking that I needed to get (in the original post) the "s" and reject the rest of the stream. But if the "char" only stores the first character entered, then I don't need to worry about that, I was also thinking that if I used the cin.ignore(); it would ignore everything, including the character that already entered.

Thanks for the help.
Topic archived. No new replies allowed.