简体   繁体   中英

Scanf skipping character in c

int main(){
    int firstNumber, secondNumber, thirdNumber;
    char oper;

    scanf("%d", &firstNumber);
    printf("%d\n", firstNumber);

    scanf("%c", &oper);
    printf("%c\n", oper);

    scanf("%d", &secondNumber);
    printf("%d\n", secondNumber);


    return 0;
}

Why this code doesn't work as expected, It reads the first and the second number but it doesn't read the character in between.

Using scanf() is hard. Here, there is a newline character left on stdin from you hitting enter after the first number. So, that's the character you read. Some format conversions ignore whitespace, but %c does not.

To make it ignore leading whitespace, you should instead use

scanf(" %c", &oper);

The space in the format string tells scanf() to ignore any whitespaces it finds, so you will read a non-whitespace character.

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