-3

This is my code but after typing input it is giving statement of default every time. Please Help.I am a beginner to C. It is not giving result.

 #include <stdio.h>
 #include <stdlib.h>
 #include <conio.h>

int main()
{
    int a;
    int b;
    char op;
    printf ("Enter first number: ");
    scanf ("%d", & a );
    printf ("Enter second number: ");
    scanf ("%d", & b );
    printf ("Enter the operator: ");
    scanf ("%s", op );
    switch(op)
    {
         case '+' : 
                       printf("Sum is %d", a+b );
         break;
         case '-' : 
                       printf("Difference is %d", a-b );
         break;
         case '*' : 
                       printf("Product is %d", a*b );
         break;
         case '/' : 
                       printf("Quotient is %d", a/b );
         break;
         default : 
                       printf("Wrong operator used!");
         break;
    }
    return 0;
}
  • 4
    I think you meant `scanf (" %c", &op );`, not `scanf ("%s", op );`. – Fred Larson Apr 05 '18 at 14:34
  • 1
    Does your even compile without warnings? `scanf ("%s", op );` is incorrect because you are passing a `char` when scanf expects a `char*`. Perhaps you meant `scanf (" %c", &op );`. – P.P Apr 05 '18 at 14:34
  • Not working...returning 0 as value....can't even enter operator now – Sameer Yadav Apr 05 '18 at 14:54
  • 1
    Please read carefully - every comment, and the answer, has a space before `%c`. Please see [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Apr 05 '18 at 14:55
  • Welcome to Stack Overflow! It looks like you forgot to enable a good set of warnings. For GCC, I recommend `-Wall -Wextra -Wwrite-strings` as a minimum; consider also `-Wpedantic -Warray-bounds` for identifying some other common mistakes. – Toby Speight Apr 05 '18 at 15:04
  • This is the point where you should start using a debugger to step through your program. That should always be the very first action to identify problems. Check your variables and where your program flow is. – Gerhardh Apr 05 '18 at 15:12
  • thnx Weather Vane and everyone – Sameer Yadav Apr 05 '18 at 15:14

1 Answers1

2

This:

scanf ("%s", op );

is undefined behavior, op is char but %s requires char * (and more than a single char of space, if you expect to actually store a string there which you don't need).

You meant:

scanf(" %c", &op); // Note the space before '%', this matters.

also always check the return values, I/O can fail.

unwind
  • 391,730
  • 64
  • 469
  • 606