为什么跳过getchar()?

时间:2015-03-05 05:19:40

标签: c io mingw mingw32 getchar

这是我下面的代码,我正在处理。输出是这样的:

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

op = getchar();部分被完全忽略。为什么?
我使用的是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 个答案:

答案 0 :(得分:3)

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

此输入后有换行符,您需要忽略它

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

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

此外,换行符由getchar()

提取