-6

I am doing a simple calculator using switch case but i ran into some problems and decided to do it in another way to check if what the user inputs is invalid but I cant make it work.

this is a piece of code from the program:

if (choice!="+"&&choice!="-"&&choice!="*"&&choice!="/");
    {
    printf("The type of operation is invalid\n");
    invalid=1;
    printf("Chose the type of operation, + for sum, - for subtraction, * for multiplication and / for division\n");
    scanf("%c", &choice);
    }

I cant verify if what the user inputs is different than +, -,, * or /.

I would love some help. Thank you in advance!

  • 3
    use `'` instead of `"` for 1 char – albttx Jan 18 '17 at 17:38
  • 2
    use single quotes around character constants. – Eugene Sh. Jan 18 '17 at 17:38
  • Possible duplicate of [How do I properly compare strings in C?](http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – Govind Parmar Jan 18 '17 at 17:38
  • Actually, since the OP didn't give us the declaration of `choice`, it could be either. If choice is a `char` you want to test against a `char`, i.e. `'+'`. If choice is a `char *` you need to test with `strcmp`. – MAP Jan 18 '17 at 17:42
  • @user2064000: Your suggestions assume `choice` is a string, what it most likely isn't (see the call to `scanf`). – alk Jan 18 '17 at 17:43
  • You also have a semicolon (`;`) after your if statement before the `{`, so the if statement will be ignored. I recommend using the syntax `if(something){` instead (with the `{` on the same line as the if statement) because it makes it less likely to make such mistakes. – Donald Duck Jan 18 '17 at 17:55

1 Answers1

2

In your code, I see the following statement:

scanf("%c", &choice);

So I am judging that the type of the variable 'choice' is char.

For character comparison, you need to use a single quote, not double quotes. So replace the

if (choice!="+"&&choice!="-"&&choice!="*"&&choice!="/");

with

if (choice!='+'&&choice!='-'&&choice!='*'&&choice!='/')

Also, remove the semicolon from the end of the if statement. It doesn't make sense.

VHS
  • 9,534
  • 3
  • 19
  • 43