Dan's
Dan's

Reputation: 21

C - OR in IF statements not working has I want

I've started learning C really recently in school, and I'm having a problem which I can't see where's the mistake. I'm currently learning functions, and I have to develop a program that calculates the area of some geometric shapes with multiple functions. That's not going so well, but the problem I have is related with OR in IF statements. I'm trying to make the user select specific charecters, otherwise it will show "Invalid option, try again". The problem is that even if the users chooses the correct chars, the "warning" will show. Sorry for bad english.

        int menu()
        {
            char opc;

        do
            {
                printf("Areas\n");
                printf("\nTriangle (nr):  \t\t\tRectangle (nr):  \n");
                printf("\nCircle (nr):  \t\t\t\tSquare (nr):  ");
                printf("\n\n\t\tOPIONS");
                printf("\n\n\t(T)riangle\n\t(R)ectangle\n\t(S)quare\n\t(C)ircle\n\t(E)nd\n\n");
                scanf(" %c", &opc);
                if((opc!='t') || (opc != 'c') || (opc != 'r') || (opc != 's') || (opc !='e'))
                   {
                        printf("\nInvalid option, try again\n");
                   }
            }
        while(opc!='e');
            return opc;

       }

Upvotes: 0

Views: 266

Answers (3)

amin
amin

Reputation: 11

you need to use && instead of || .because if the first condition is true ,I mean user input a character other than 't' ,compiler won't check next condition and whole expression will get true.

Upvotes: 0

Kalina Mielke
Kalina Mielke

Reputation: 111

't'!='c', 'c'!='r' etc so no letter is correct - you meet the condition for all letters.

Upvotes: 0

0___________
0___________

Reputation: 67820

You want:

if((opc!='t') && (opc != 'c') && (opc != 'r') && (opc != 's') && (opc !='e'))

In your code, opc can have only one value always at least 5 conditions will be true. If one of the conditions is true, the whole expression is true. So it is always the true despite the value of opt

Upvotes: 2

Related Questions