English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How would I use an if statement to form a condition for letters of the alphabet. For example, if I want to assign A through D to "first class" and D thru Z to "second class" ?
User will input a letter in either upper or lower case and the output should be either "first class" or "second clas". How do it do this?

I know how to get the input and the letter but I don't know how to make the range A - D. Is there a way apart from the long way of doing (If x = a....or.....or....or....or..) else (cout<

2007-05-06 20:21:49 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

I think first, I would convert lower case to upper case letters
(but you dont need to). Then its pretty simple.
char x;
cin>>x;
toupper(x);//not sure of the actual syntax
if (x >= 'A' && x < 'E')
cout<<"first class";
else
cout<<"second class";

without converting to upper case first:

char x;
cin>>x;
if ((x >= 'A' && x <'E') || (x >= 'a' && x <= 'e'))
cout<<"first class";
else
cout<<"second class";

you may also want to make sure x is a letter and not a number first though. or you could change the "else" to:

else if ((x > 'D' && x <= 'Z') || (x >= 'd' && x <= 'z'))
cout<<"second class";
else
cout<<"not a letter";

2007-05-07 01:15:46 · answer #1 · answered by justme 7 · 0 0

Compare ASCII codes of the letters:
a thru z = 97 thru 122 (d = 100)
A thru Z = 65 thru 90 (D = 68)

Use int(letter) to get the ASCII code.

2007-05-06 20:49:12 · answer #2 · answered by Andrei M 3 · 1 0

C++ is not a great language for working with string. I would recommand Perl if you work with string intensively. Back to your question, i think there is not a way to make a range A-D as you described, though you can try switch statement to make your code look better.

2007-05-06 20:40:03 · answer #3 · answered by basch2007 1 · 0 1

fedest.com, questions and answers