0
#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!

  • Please use the `scanf(" %c")` you mentioned, rather than kludges: it is the way `scanf` is intended to be used. The `scanf` conversion stops at the first character it cannot convert, which is typically (but not necessarily) a space or a newline, and that character remains in the input buffer. It will be read by the *next* `scanf()`. Format specifiers `%d` and `%s` and `%f` automatically filter leading whitespace characters, but `%c` and `%[]` and `%n` do not. You can instruct `scanf` to do so by adding a space just before the `%`. – Weather Vane Jan 18 '22 at 17:27
  • Thanks, I got that but if I use `scanf("%c")` at start just after declaring the variable then it takes input normally, can you help explaining that ? – Piyush Chauhan Jan 19 '22 at 12:28
  • Why shouldn't it? There hasn't been any previous input, that would leave a newline in the input buffer. – Weather Vane Jan 19 '22 at 20:11
  • I see, understood Thanks. – Piyush Chauhan Jan 22 '22 at 14:31

0 Answers0