Detecting ASCII???

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Detecting ASCII???

Postby mr_cheeks » Sun Oct 05, 2003 11:29 pm

detecting ASCII???
I have created a file and have populated it with names and their gender (male or female). Gender can either be inputted as a M or as an F by the user....If the user enters anything else, an error message should appear.
I initially tried this:

if( ( gender == "m" ) || ( gender == "m") )
{
then write to file
}


but the file did not accept any input.

I then tried this

if( ( gender == '10101001' ) || ( gender == '10100010' ) )
taking the ASCII code for m and f but I got a compile error (i beleive since i defined gender to be of char type).

How do i code : do not accept any other letters for gender besides M,m,F or f (case sensitive???).

THANK YOU.
mr_cheeks
 
Posts: 3
Joined: Sun Oct 05, 2003 9:10 pm
Location: montreal

Detecting ASCII???

Postby madhu » Mon Oct 06, 2003 12:38 am

char should be compared with single quotes like this:

if( ( gender == 'm' ) || ( gender == 'M') )
madhu
 

Postby Justin » Tue Oct 07, 2003 1:43 am

Code: Select all
if( ( gender == '10101001' ) || ( gender == '10100010' ) )


That's not ASCII, it's binary. In fact, it's not even binary, it's a literal since you have it in quotes, in fact! it's a compiler error because you have a literal of more than one character in single quotes when it should be double quotes. According to VC++ 6.0, it is "error C2015: too many characters in constant."

Anyway, if you want to compare ASCII values, you need to do the following.Try something like this:
Code: Select all
if (int(gender) == 77 || int(gender) == 109 ||  // 'M' and 'm'
  int(gender) == 70 || int(gender) == 102) {  // 'F' and 'f'
  // Do something neat
}


Technically, you don't have to explicitly typecast the char variable, but sometimes it's nice so that you can remember what you're doing, especially when you're new.
User avatar
Justin
 
Posts: 158
Joined: Tue Sep 30, 2003 10:07 am
Location: CA

Postby omnius » Tue Oct 07, 2003 3:34 pm

Code: Select all
if (int(gender) == 77 || int(gender) == 109 ||  // 'M' and 'm'
  int(gender) == 70 || int(gender) == 102) {  // 'F' and 'f'
  // Do something neat
}


Ugghhh! 'M' and 'm' are so much more readable than 77 and 109, and remove the need for the comment. ;-)
omnius
 
Posts: 496
Joined: Wed Sep 24, 2003 12:03 pm

Postby Justin » Wed Oct 08, 2003 8:11 pm

I completely agree, I thought that's what he wanted to do though, since he was coming out with the binary and all
User avatar
Justin
 
Posts: 158
Joined: Tue Sep 30, 2003 10:07 am
Location: CA


Return to For Beginners

Who is online

Users browsing this forum: No registered users and 1 guest