How does the buffer work using printf and scanf?

2

Using printf , when I do:

printf("\n\tQualquer coisa\n");

It inserts this first into a buffer and then prints to the screen (standard output)?

Using scanf with the format %c , it captures the character-to-character buffer. But when I use the %s format? It stops when it finds a space or enter, but does it leave that enter or buffer space? If yes, how can I read something from the buffer and not capture it?

And in case of these scanf :

scanf("%c\n", &caracter);
scanf("%s\n", string);

These scanf above reads from the buffer a character (for %c ) and a string (for %s ) and remove the buffer the next enter? What happens ? What do these characters mean within the quotation marks? I always imagined that in% w / o%, the first parameter was only the formats to be read.

I would like you to explain me in detail, because in class and in books, the explanations are superfluous, and I know that the operation of this is not very simple. If there is any documentation that reports well the behavior of this, please pass the link to me, because I searched the C standard and did not find it.

Thank you.

    
asked by anonymous 07.11.2014 / 13:48

1 answer

1

Hello, the problem is that when reading a string with more than one word (with spaces) it stops reading only the first word. An example would be the string "My house", if we use the syntax above it will only store the word "Mine", stopping to find the space.

What we can do to correct this error is to force the scanf to read the string until it finds the [enter], so we must insert the following code:

scanf("%[^\n]s", string);

Parameters passed between the scanf or printf quotes are read or output properties that C makes available to you. In your code it is only telling you that it will read a string and give a line break after the variable.

\n = quebra de linha

To find out how broad this is, the example below will read all the letters of the alphabet by ignoring numbers typed!

scanf("%[a-z A-Z]s");
    
07.11.2014 / 14:09