0

Ok, I know you aren't suppose to (or can't) do comparions on arrays such as, if (x < y), when both x and y are single dimensional arrays. But what about if you have a string and want to compare one element in that string. For example, I am trying to do:

if (studentId[3] == 1)
    cout << "Freshman ";

else if (studentId[3] == 2)
     cout << "Sophmore ";

else if (studentId[3]  == 3)
     cout << "Junior ";

else if (studentId[3] == 4)
     cout << "Senior ";

The fourth character in the string is either 1, 2, 3, 4. My program compiles, but it just skips this section. I placed a cout << studentId[3]; statement right before this to see if I am passing the studentId correctly....I am because the program spits out the correct studentId[3] every time. I searched other people's code on this website, and it seems others are writing comparisons like this in their code. Any tips on how I can move further or what I am doing wrong? Thank you!

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by teppuus
1

If you want the character representation of a digit, wrap it in single quotes:

if (studentId[3] == '1')
    cout << "Freshman ";

else if (studentId[3] == '2')
     cout << "Sophmore ";

else if (studentId[3]  == '3')
     cout << "Junior ";

else if (studentId[3] == '4')
     cout << "Senior ";
0

Thank you. That did the trick. I didn't know that all components in a string are characters, even if they are numbers.....which makes since. That helped me solve a problem I was having during error checking as well. Thank you! It is always great to learn something new.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.