-4

this is my first post here. i started learning software engineering this month and i'm tring to code a software using c. i cant found the mistake to change it .. can anyone help me please!

    #include <stdio.h>
    void main()
    {
        int a,b,e;
        char operation;
        printf ("enter the first number:");
        scanf ("%d",&a);
        printf ("enter the second number:");
        scanf ("%d",&b);
        printf ("enter the operation:");
        scanf ("%c", &operation);
        switch (operation)
        {   case '+' :  e=a+b;
            break;
            case '-' :  e=a-b;
            break;
            case '*' :  e=a*b;
            break;
            case '/' :  e=a/b;
            break;
            default: printf("wrong choice!!");
    
        }

    printf("%d %c %d = %d \n", a, operation, b, e);
    }
Jaouadi
  • 3
  • 1

2 Answers2

0
#include <stdio.h>
    void main()
    {
        int a,b,e;
        char operation;
        printf ("enter the first number:");
        scanf ("%d",&a);
        printf ("enter the second number:");
        scanf ("%d",&b);
        getchar();
        printf ("enter the operation:");
        scanf ("%c", &operation);
        switch (operation)
        {   case '+' :  e=a+b;
            break;
            case '-' :  e=a-b;
            break;
            case '*' :  e=a*b;
            break;
            case '/' :  e=a/b;
            break;
            default: printf("wrong choice!!");
    
        }

    printf("%d %c %d = %d \n", a, operation, b, e);
    }

your scanf ("%c", &operation); is reading a newline character \n from the above scanf statement. so, to scan the operation statement properly you have to add getchar() which detect the newline character \n.

vegan_meat
  • 878
  • 4
  • 10
0

As already mentioned by @Oka scanf() leaves the new line char in the buffer.

You have to discard the newline character, you can simply use getchar() function before the last scanf to discard that single character (could be newline char or not), to be 100% sure about discarding all the unread characters from input buffer you can do

while((c = getchar()) != '\n' && c != EOF)

Or else can use " %c" (whitespace %c) to ignore the leading newline character.

Linux Geek
  • 957
  • 1
  • 11
  • 19