For single characters, you have two options:
1) If the user inputs more than one character, reject the input and prompt the user for a new input, or
2) Just take the first character the user inputs and discard whatever else the user might have entered after that (if anything).
For #2, you can just do
1 2 3
|
char ch;
cin >> ch; // Grab the first character
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Need #include <limits> for this
|
The third line there just tells
cin to discard as many characters in the input stream as possible until it reaches a newline character (from the user pressing Enter).
http://www.cplusplus.com/reference/istream/istream/ignore/
For #1, you can use
cin.get() to read the next character in the input stream. If the user only entered one character, then the next character should be the newline character (
'\n'
); otherwise, it'll be something else.
1 2 3 4 5 6 7 8 9 10 11 12
|
char ch;
while (true)
{
cin >> ch; // Grab the first character
if (cin.get() != '\n') // Look at the next character
{
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clear the input stream
cout << "Hey! Only one character, please: ";
}
else
break;
}
|
(or something similar to this)
For strings, just use a similar loop so that if the user enters something that you don't want, then go back and get a new input.