Overclock.net banner

Boolean comparisons with Chars?

805 Views 3 Replies 3 Participants Last post by  rabidgnome229
Hello,

in my C class I'm one step away from completing my program with all of the required output and details. The one thing I'm stumped on is data validation.

Basically, I read from an input file in a specific format. The first value is a char that can either be, C, c, T, t, B, b. They stand for car, truck, and bus and are put into a switch.

I do fscanf to read from the file, but if someone uses a data file with say, a first value that is like X, or V, or straight up "feces", I want the program to terminate.

Problem is, I can't simply do

if (*vehicle != 'c' || 'C' || ...) because boolean operators, I assume(that's what visual studio says), are inoperable with chars.

I can post my code if it is necessary.

Thank you.
1 - 4 of 4 Posts
You can convert to int and use the ascii values..
  • Rep+
Reactions: 1
i actually figured out an easier way to do it since i've haven't had experience with data type conversions yet, i just read in the char alone by itself and checked it against a switch.

thanks for your input though
You want

Code:

Code:
if (*vehicle != 'c' && *vehicle != 'C' && ...)
Every value that you || or && together should be a boolean expression (a == b, a != b, etc). If you do

Code:

Code:
if (*vehicle != 'c' || 'C')
This is equivalent to

Code:

Code:
if ((*vehicle != 'c') || 'C')
Here 'C' is evaluated as a boolean. Since the value of the ascii character 'C' is nonzero it is taken to be true. Because of this your if statement will always evaluate to true.

It's as if you wrote the following

Code:

Code:
if((*vehicle != 'c') || ('C' != 0))
And ('C' != 0) is a true statement
See less See more
1 - 4 of 4 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top