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

Similar Threads

C++ rounds up my decimals 10
TF-IDF 1
Help in hangman game 1
input to cin 58
input revisted 0
Identifier not declared? 1
Will someone tell me how to handle only input between -1 and 100.? 2
sort input 7

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top