Easier way to do this?

I want to read a letter from the user that is between a and j including a and j.

Here is my attempt:

1
2
3
4
5
6
7
8
if (userInput != 'a' || userInput != 'b' || userInput != 'c' ||
        userInput != 'd' || userInput != 'd' || userInput != 'e' ||
        userInput != 'f' || userInput != 'g' || userInput != 'h' ||
        userInput != 'i' || userInput != 'j')
    {
        cout << "Invalid letter. Please try again: ";
        cin >> userInput;
    } 


I understand this isn't very efficient. I looked at ASCII table and the value of a is 96 and the value of j is 106, how can I construct a loop knowing the ASCII values of these letters?

Also, I apologise for posting so many threads. One of the best ways to learn is to ask questions whenever you're stuck.
Last edited on
> I looked at ASCII table and the value of a is 96 and the value of j is 106,
> how can I construct a loop knowing the ASCII values of these letters?

The implementation may not be using an ASCII encoding for characters.

Portable, non-palooka:
1
2
const std::string valid_letters = "abcdefghij" ;
if( valid_letters.find(userInput) == std::string::npos ) std::cout << "invalid letter.\n" ;
if ( userinput >= 'a' && userinput <= 'j'){
// to do
}
JLBorges has the super legit, least amount of code for this procedure (I'm assuming), but here's a simpler version of input validation using a do-while loop:

1
2
3
4
5
6
do
{
	cout << "Enter a letter between a and j: ";
        cin >> userInput;

} while(userInput < 'a' || userInput > 'j');
Thank you very much guys!
Topic archived. No new replies allowed.