-1
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.

Cyber Gh
  • 162
  • 3
  • 8

1 Answers1

1

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.

FatalError
  • 50,375
  • 14
  • 97
  • 115