Input should allow only alphabetical letters, regardless of case

E

Eric Lilja

Hello, in my program I need to ask the user to input some alphabetical
letters. Case should not matter. Any input that isn't an alphabetical letter
should be rejected and the user prompted to try again.
I came up with:

std::cout << "Type a letter: ";

char c = '\0';

while(!(std::cin >> c) || !std::isalpha(c))
{
std::cerr << "That wasn't a valid alphabetical letter, please try again:
" << std::flush;

if(!std::cin)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}


It seems to work, but I was wondering if it needs more robustifying without
going to ridicolous lengths to achieve it?

/ E
 
R

Rapscallion

Eric said:
Hello, in my program I need to ask the user to input some alphabetical
letters. ....
while(!(std::cin >> c) || !std::isalpha(c))

Use could instead try:
string tmp;
getline (cin, tmp);
// parse tmp ...
{
std::cerr << "That wasn't a valid alphabetical letter, please try again:
" << std::flush;

if(!std::cin)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}

It seems to work, but I was wondering if it needs more robustifying without
going to ridicolous lengths to achieve it?

What do you expect from a language like C++?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top