Search code examples
ciomingwmingw32getchar

Why is getchar() being skipped?


This is my code below, which I was working on. The output is this:

Enter Nums: 20 4
OP: Which option was that?

The op = getchar(); part is being entirely ignored. Why?
I'm using gcc 4.6.2 MinGW.


#include <stdio.h>
int add(int num1, int num2) {
    return num1 + num2;
}

int subs(int num1, int num2) {
    return num1 - num2;
}

int mul(int num1, int num2) {
    return num1 * num2;
}

float div(int num1, int num2) {
    return (float)num1 / num2;
}

int main(int argc, char* argv[]) {
    int num1, num2;
    char op;
    fprintf(stdout,"Enter Nums: ");
    scanf("%d %d",&num1,&num2);
    fprintf(stdout, "OP: ");
    op = getchar();
    switch(op) {
    case '+':
        printf("%d",add(num1, num2));
        break;
    case '-':
        printf("%d", subs(num1,num2));
        break;
    case '*':
        printf("%d",mul(num1,num2));
        break;
    case '/':
        printf("%f",div(num1, num2));
        break;
    default:
        printf("Which option was that?\n");
    }
    return 0;
}

Solution

  • scanf("%d %d",&num1,&num2);
    

    There is a newline character after this input and you need to ignore it

    scanf("%d %d%*c",&num1,&num2);
    

    or

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

    Else the newline is picked up by the getchar()