Problem reading characters with Scanf in C

2

I have a problem with the following program:

#include <stdio.h>

int main()
{
    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;
}

It only lets me read the first character and then the program ends. The output is as follows:

Ingrese el primer caracter: a 
Se leyó el caracter: a 
Ingrese el segundo caracter:
Se leyó el caracter:

Thank you.

    
asked by Nicolas F. 02.08.2017 в 18:58
source

2 answers

1

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;
}
    
answered by 02.08.2017 / 19:01
source
-1

I solved it in a different way but it worked for me, the demonstration that you did explains everything better. I solved it by putting two scanf followed like this:

int main()
{
    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);
    scanf("%c", &b);
    printf("Se leyó el caracter: %c\n", b);
    return 0;
}
    
answered by 27.11.2018 в 14:59