Why is getchar() being skipped? [duplicate]

送分小仙女□ 提交于 2019-12-02 17:28:29

问题


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;
}

回答1:


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()



来源:https://stackoverflow.com/questions/28870562/why-is-getchar-being-skipped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!