Why do we need to use flush() when we use print!()?


#1

Hello everyone,

I wonder why we needed to use io::stdout().flush(); when we use the print!() instruction ?
Because if not, the program will print the message after user input.

Kind regards


#2

Consoles are typically line-buffered, but the flush causes the buffer to be written without having completed the line with '\n'.


#3

Hello cuviper,

Thanks for your answer.
So to be printed on a terminal a line must have an “end character” which equals “\n” for newline ? I thought it was just a character for new line but didn’t know that it was also a character to say “End of buffer” !


#4

Normally your OS will buffer output by line when it’s connected to a terminal, which is why it usually flushes when a newline is written to stdout. If you want to write only part of a line to the console (i.e. without a \n at the end) you’ll need to manually tell the OS to flush output to the terminal.

This article mentions:

Default Buffering modes:

  • stdin is always buffered
  • stderr is always unbuffered
  • if stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered