Redefender Redefender - 1 year ago 85
C++ Question

Validating if single char is char

I want to validate if a char is actually a char. When user inputs a string of letters "abc" program will say that user must enter a single char.

I was thinking about using

if(sizeof(userLetter != 1))
cout << "Enter only a single letter."

The problem is since userLetter is initialized as a character it automatically truncates remainder of letters and thinks user only input one letter.

Is there a way to check if user really only input 1 letter without initializing userLetter as a string?

Answer Source

If your reading a char, it will only read one and keep the following chars in the buffer.

If you want to take all what the user types until he presses the first enter, you need to get a line:

 string line; 
 while (getline(cin, line) && (line.length()==0 || line.length()>1) )  
    cout << "Enter only a single letter..."<<endl; 

When this ends successfuly, get the first char of string with userLetter = line[0];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download