C handles buffers, both input and output. What the function scanf
does is go to the input buffer stdin
and try to remove the format you indicated (in this case, a char). In the first case, as the buffer is empty, the program will wait for you to enter something by keyboard, in your case you entered a a
and pressed the% key% of% which was interpreted as a enter
. At this time the input buffer will have the following \n
. The function a\n
will remove the character scanf
and return to the program. The second a
will do the same as the first one, but this time you will find something in the input buffer, the scanf
. C interprets the \n
as a character and prints it on the screen (it can not be seen because the console interprets it as a line break).
Solution:
To make \n
with individual characters, I added a blank space before scanf
to skip any white space and line breaks.
scanf(" %c", &ch);
For the %c
and %d
formats this is done automatically and the white space is not necessary.
Beware: there is a solution for %s
before fflush(stdin)
to clean the input buffer. This is not correct because scanf
is only defined for output streams, the behavior with fflush
is not defined (although in some environments it is an error to use it).
I also recommend not leaving functions that do not receive implicitly blank parameters. Use the word stdin
asi: void
Your code would look like this:
#include <stdio.h>
int main(void)
{
char a, b;
printf("Ingrese el primer caracter:\n");
scanf(" %c", &a);
printf("Se leyó el caracter: %c\n", a);
printf("Ingrese el segundo caracter:\n");
scanf(" %c", &b);
printf("Se leyó el caracter: %c\n", b);
return 0;
}