0

I want to read a single character from the console, but when I do, the program reads characters yet and I must write another character to save the first and finish its execution.

Code:

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>

char peps;
int main(int argc, char const *argv[]) {
    printf("write a character:\n");
    scanf(" %c\n", &peps);
    printf("%c\n", peps);
    return 0;
}

Can anyone explain why it does that and how to correct this error?

Jens
  • 69,818
  • 15
  • 125
  • 179
EmmanCanVaz_95
  • 123
  • 1
  • 8

1 Answers1

1

If you remove the \n from the scanf(), it should work as you want.

ie, do

scanf(" %c", &peps);

instead of

scanf(" %c\n", &peps);

This is because the \n in the scanf() format string is telling the computer to read and ignore all white spaces (including \n) after reading a character.

So all white spaces including the newlines given by typing the enter key, would be ignored. This will stop only when a non-white space character is encountered which won't be read and would thus remain in the input buffer.

So, in your case, a character would first be read and it would wait for a non-white space character before executing the printf() following the scanf(). The non-white space character would remain in the input buffer and was not read and is hence not printed at once. It would be read only upon reading from the stdin again.

If you want to explore this further, consider placing that scanf() and printf() in a loop and examine the output.

Note that replacing that \n with a space would have the same effect.

ie,

scanf(" %c\n", &peps);

and

scanf(" %c ", &peps);

would have the same behavior.

What's the behavior of scanf when the format string ends with a newline?

Behaviour of scanf when newline is in the format string

J...S
  • 5,079
  • 1
  • 20
  • 35