2 years ago

#66388

test-img

Piyush Chauhan

Scanf not working properly with "%c" but works

#include<stdio.h>
int main(){
    char mathoperation;
    int num1,num2;
    printf("Give the first number of you opperation : ");
    scanf("%d",&num1);
    printf("Give the second number of you opperation : ");
    scanf("%d",&num2);
    printf("Give the math operation you want to use : ");
    scanf("%c",&mathoperation);

    switch (mathoperation)
    {
    case '+':
        printf("%d\n",num1+num2);
        break;
    case '-': 
        printf("%d\n",num1-num2);
        break;
    case '*':
        printf("%d\n",num1*num2);
        break;
    case '/':
        if(num2==0)
            printf("No you cant do that");
        else
            printf("%d\n",num1/num2);     
        break;
    case '%':
        printf("%d\n",num1%num2);
        break;
    default:
        printf("Error!");
        break;
    }
        return 0;
}

When I use "%c" in above code it doesn't take any input and go to default: directly The output but if I use scanf(" %c") instead of scanf("%c") it works It also works If I use scanf("%c"); before using scanf("%d"); it works . Please help!

c

scanf

0 Answers

Your Answer

Accepted video resources