How does buffer work using printf and scanf?

Using printf, when I do:

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

Does it insert this first into a buffer and then print to the screen (default output) ?

Using the scanf format %c, it captures character by character from the buffer. But what about when I use the %s format ? It stops when it finds a space or enter, but does it leave that enter or space in the buffer ? If so, how can you read something from the buffer and not capture it ?

And in the case of these scanf :

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

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

I wish you could explain me thoroughly, because in class and in books, explanations are superfluous, and I know that it is not quite simple how it works. If there is any documentation that reports Well the behavior of this, please pass me the link, because I searched the C standard and did not find.

Grateful.

Author: ViniciusArruda, 2014-11-07

1 answers

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

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

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

The parameters passed between the quotes of the scanf or printf are read or output properties that C gives you. In your code it is just telling you that it will read a string and give a line break after the variable.

\n = quebra de linha

To know how broad This is, the example below will read all letters of the alphabet ignoring numbers typed!

scanf("%[a-z A-Z]s");
 1
Author: vmontanheiro, 2014-11-07 13:09:16