-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
  • 180
  • 3
  • 8
  • Read [documentation of `scanf`](https://en.cppreference.com/w/c/io/fscanf). You should test its return count. Read also [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Basile Starynkevitch Oct 31 '18 at 20:03
  • Define "something weird". – meowgoesthedog Oct 31 '18 at 20:03
  • by weird i mean it doesn't read it, just kinda skips it i think – Cyber Gh Oct 31 '18 at 20:05
  • 2
    Possible duplicate of [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – Achal Oct 31 '18 at 20:05

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
  • 52,695
  • 14
  • 99
  • 116