Reputation: 1002
i need to restrict the user from inputting an integer and string when inputting a char. I have a method for an integer i just need to adapt it for a char. Can anyone help me with this.
char getChar()
{
char myChar;
std::cout << "Enter a single char: ";
while (!(std::cin >> myChar))
{
// reset the status of the stream
std::cin.clear();
// ignore remaining characters in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ^^^ This line needs to be changed.
std::cout <<
"Enter an *CHAR*: ";
}
std::cout << "You entered: " << myChar << std::endl;
return myChar;
}
char getChar()
{
char myChar;
std::cout << "Enter an Char: ";
while (!(cin >> myChar))
{
// reset the status of the stream
cin.clear();
// ignore remaining characters in the stream
cin.ignore(std::numeric_limits<char>::max() << '\n');
cout << "Enter an *CHAR*: ";
}
std::cout << "You entered: " << myChar << std::endl;
return myChar;
}
I have tried this and there are no errors. But it does not woek.
Upvotes: 1
Views: 3668
Reputation: 1002
I changed the methid to this:
char getChar(string q)
{
char input;
do
{
cout << q.c_str() << endl;
cin >> input;
}
while(!isalpha(input));
return input;
}
And in my main i have:
string input = "What is your sex M/F?"; char sex = getChar(input); cout << sex <<"\n";
Doin this, i am not allowed enter a number wen asked what the sex is.
Upvotes: 0
Reputation: 409136
I'm guessing by "does not work" you mean that even when you enter a longer string or a number it's still accepted. That's because all letters and digits input via the <<
operator is still a single character.
You have to add another check if you don't want non-alphabetic characters:
while (!(std::cin >> myChar) || !std::isalpha(mychar))
See this reference for an explanation of std::isalpha
.
Upvotes: 3