Home > database >  C - OR in IF statements not working has I want
C - OR in IF statements not working has I want

Time:11-27

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;

       }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related