HarryHL
HarryHL

Reputation: 9

If statement returns wrong output C++

I have a if field containt a simple expression I can't find out what is causing the issue, the statement is produced no matter what figure is used

if (pos != string::npos)
{
    mystring.erase (0,10);
    {
        int numb;
        istringstream(mystring)>>numb;
        cout << numb << endl; //to check the numb integer (its equals 2)
        if (numb != 1,2,3)
        {
            cout << "Please attach a valid priority to this ticket" << endl;
        }        
        else
            cout << "nice one" << endl; 

For some reason (That I can't figure out) the programme returns the "Please attach a valid priority to this ticket" regardless of what the numb is.

Help would be much appreciated!

Upvotes: 0

Views: 147

Answers (3)

dfranca
dfranca

Reputation: 5322

You are probably receiving a warning from your compiler... if you aren't, check the warning parameters. The comma operator discard the results from the previous operands and return only the last one. In this case the if is the same as:

if (3)

Which, for sure, is not what you want. In your case, if you just want to check if a integer number is not in the interval 1 to 3, you can check this way:

if (num < 1 || num > 3)

Upvotes: 1

Zeta
Zeta

Reputation: 105955

// read a ~ b as "a is equivalent to b"
(numb != 1,2,3) ~ ((numb != 1),2,3) ~ (2,3) ~ 3

Therefore, your condition is always true. You need to combine logical results (booleans) with && (and) or || (or), for example:

if (numb < 1 || numb > 3)

Upvotes: 1

Barmar
Barmar

Reputation: 782407

if (numb != 1, 2, 3) 

should be:

if (numb != 1 && numb != 2 && numb != 3)

What you write is parsed as:

if ((numb != 1), 2, 3)

This uses the comma operator, which evaluates each of its arguments and returns the second argument. So it's equivalent to:

if (3)

Upvotes: 5

Related Questions