Sunday, July 12, 2009

C++ - IF statements with strings?

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%26lt;%26lt;second class")

C++ - IF statements with strings?
I think first, I would convert lower case to upper case letters


(but you dont need to). Then its pretty simple.


char x;


cin%26gt;%26gt;x;


toupper(x);//not sure of the actual syntax


if (x %26gt;= 'A' %26amp;%26amp; x %26lt; 'E')


cout%26lt;%26lt;"first class";


else


cout%26lt;%26lt;"second class";





without converting to upper case first:





char x;


cin%26gt;%26gt;x;


if ((x %26gt;= 'A' %26amp;%26amp; x %26lt;'E') || (x %26gt;= 'a' %26amp;%26amp; x %26lt;= 'e'))


cout%26lt;%26lt;"first class";


else


cout%26lt;%26lt;"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 %26gt; 'D' %26amp;%26amp; x %26lt;= 'Z') || (x %26gt;= 'd' %26amp;%26amp; x %26lt;= 'z'))


cout%26lt;%26lt;"second class";


else


cout%26lt;%26lt;"not a letter";
Reply: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.
Reply: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.


No comments:

Post a Comment