简体   繁体   中英

Switch statement isnt working properly while I'm using getchar()?

I need to write a program that goes through a for loop 4 times, and gets the user input. It can either be + , - , * or / . Otherwise it will print out invalid operator . When I run this program and put in + , it outputs f = 30 (which I want) but then it outputs invalid operator right under it without me even putting in another character. Then I enter - and it outputs invalid operator twice. Can someone explain why this is happening?

#include <stdio.h>
#pragma warning(disable : 4996) 

void main() {
    char ch;
    int f, a = 10, b = 20;
    for (int i = 0; i < 4; i++) {
        ch = getchar();
        switch (ch) {
        case '+': f = a + b; printf("f = %d\n", f);
            break;
        case '−': f = a - b; printf("f = %d\n", f);
            break;
        case '*': f = a * b; printf("f = %d\n", f);
            break;
        case '/': f = a / b; printf("f = %d\n", f);
            break;
        default: printf("invalid operator\n");
            break;
        }
    }
}

这里的问题是,当你进入操作,输入操作员然后按Enter键,以及回车键增加了输入缓冲区,你会读出但尚未办理换行。

fflush(stdin);

When you received a input from ch=getchar() , you input one character and press enter, newline character is added in the input buffer too.

Try to use fflush(stdin) or while(getchar()!='\\n');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM