Reputation: 2883
I have an if statement that looks as follows:
int count=0;
string Check;
if ((count==4 && Check!="-s")||(count==4 && Check!="-S"))
If count
equals 4 and Check
equals "-s"
or "-S"
it still enters this if
statement because of the count == 4
. It totally seems to ignore the second part. Is there something I'm doing wrong?
Upvotes: 1
Views: 165
Reputation: 2726
You want to enter the if body if and only if Check is != from either -s or -S and count is = 4 right?
if ( (Check!="-s" && Check!="-S") && count==4 )
should work.
or
if ( Check.tolower() !="-s" && count==4 )
should work.
(Do not remember the name of the function to lowercase a string, you have got to look it up)
Hope this help.
Upvotes: 1
Reputation: 3766
Might be more clear to use:
if (count==4 && Check!="-s" && Check!="-S")
Upvotes: 2
Reputation: 173
The right statement is:
if(count==4 && (Check != "-s" || Check!="-S"))
The statement that you wrote is true if you have count = 4 and Check = "-S" because then the first part of the OR is true.
Upvotes: 2
Reputation: 131837
Well, if Check
is "-S"
, then it will not even check the second pair of conditions, because you check with ||
. The same holds true for the opposite case. If one is false, the other is true. Replace that with a &&
.
int count = 4;
string Check = "-S";
if( (count == 4 && // count is 4, alright.
Check != "-s") || // Check is "-S", alright I'm done thanks to || (OR)
(count == 4 &&
Check != "-S") )
{
// ...
}
int count = 4;
string Check = "-s";
if( (count == 4 && // count is 4, alright.
Check != "-s") || // Check is "-S", time to check the other condition pair...
(count == 4 && // count is 4, alright.
Check != "-S") ) // Check is "-s", which is different from "-S", perfect.
{
// ...
}
Now the corrected version:
int count = 4;
string Check = "-S";
if( (count == 4 && // count is 4, alright.
Check != "-s") && // Check is "-S", different from "-s", now on to the other condition!
(count == 4 && // count is 4, alright.
Check != "-S") ) // Check is "-S"... oh dang! No executed code for you.
{
// ...
}
Upvotes: 2
Reputation: 6847
You should use !strcmp(Check, "-s") and !strcmp(Check, "-S") instead of !=.
If you use == you compare the pointers and that is no what you want. The pointers will always be different thus your second argument will always be true.
Upvotes: 1
Reputation: 17376
It's always going to be the case that either Check!="-s"
or Check!="-S"
. Hence, your if statement is equivalent to if (count==4)
.
Upvotes: 4
Reputation: 23142
If count == 4
and Check == "-s"
, then the expression to the right of the ||
is true. If count == 4
and Check == "-S"
, then the expression to the left of the ||
is true. So you have true or true which is true. Thus, your if-block is executed.
Upvotes: 2