You doubt scan character C

0

I'm starting with C and although I know I should do it, I do not understand why I should put a line break before scanning the character.

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

#include <stdio.h>

int main()
{
    printf("Cadena: "); scanf("%s", str);
    printf("Char: "); scanf("\n%c", &c);

    return 0;
}
    
asked by Morfeo WS 18.11.2018 в 18:07
source

1 answer

2

When scanf() you pass the format string "%s" will read all the characters found in the input to the first "space", considering as such the ASCII 32 (space character), the ASCII 9 (tabulator ) or ASCII 10 or 13 (carriage return and new line). When he finds one of these "targets", he does not read them. In the variable str you will have all the characters you have read up to that target.

The problem is that the target you have not read, remains there, in the input buffer, waiting. The next routine that makes use of the standard input will find that target as the first character. Normally, if the following scanf() uses format string "%d" or "%f" , or "%s" , this poses no problem, because those format strings will ignore all "blanks" until they find the first non-target character and there they begin their reading.

But when you have a "%c" problems appear, since this format string simply means "read a character", whichever it is, whether it is blank or not. Therefore scanf() would find the blank that had remained unread from% previous%, and that would be the character that would read.

It is common for the user, after typing your entry in your first scanf() , press return of car. Since the carriage return is considered "white", it would not be part of the string read in scanf() , but it would be in the buffer as I explained, and the next str would find it and leave you in scanf("%c", &c) that carriage return (ASCII 13).

To avoid it there are several techniques. One of them is the one you used to indicate to c that before the character you are interested in comes a carriage return, putting scanf() as a format string.

Another common technique is to make a "\n%c" after the first getch() in order to "consume" the blank that had not been read, whether it is a carriage return or another type of target.

    
answered by 18.11.2018 / 18:21
source