Overclock.net banner

1 - 4 of 4 Posts

·
Banned
Joined
·
2,053 Posts
Discussion Starter #1
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.
 

·
Banned
Joined
·
2,053 Posts
Discussion Starter #3
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
 

·
Premium Member
Joined
·
5,282 Posts
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
 
1 - 4 of 4 Posts
Top