Leon
Leon

Reputation: 13

Error of wrong char, even when the char is correct

I have an assignment on matrix operations and I cannot figure out what is wrong in my code, that makes my program say that char is wrong, even though it is correct. Could you please help me? Thank You.

if(scanf(" %c", &symbol) == 1)              //input symbol with error handling
    {
        if (symbol != '*' || symbol != '+' || symbol != '-')
        {
            printf("[%c]\n", symbol);
            fprintf(stderr, "Error: Chybny vstup [Symbol]!\n");
            return 100;
        }
    }  

enter image description here

Upvotes: 0

Views: 63

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

You need to use the logical AND operator && instead of the logical OR operator ||

if (symbol != '*' && symbol != '+' && symbol != '-')

Otherwise the condition of the if statement

if (symbol != '*' || symbol != '+' || symbol != '-')

will always evaluate to logical true for any character.

You could avoid the mistake if you used the negation operator the following way

if ( !( symbol == '*' || symbol == '+' || symbol == '-' ) )

Upvotes: 1

Related Questions