Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Why does this code only work when using '\n'?

Tags:

c++

delay

The following C++ code works fine when compiling with g++ on Ubuntu 18.04:

#include <iostream>

using namespace std;

void wait(){
  int t0 = time(0);
  while(true){
    if(time(0) >= t0 + 1){
      return;
    }
  }
}
int main(){
  while(true){
    cout << "tick\n";  //Line 15
    wait();
  }
}

This is the output where one tick appears every second:

tick
tick
tick
tick
tick

However when removing the \n in line 15 it seems to just be stuck somewhere and nothing happens. What exactly is \n doing to the code? What do I do if I don't want to print in a new line after every cycle? (I assume that calling this a bug in C++ would be a bit arrogant and wrong)

Also, I know that this is probably a very bad way of building a delay function, I'm just messing around a bit.

like image 318
EVARATE Avatar asked Dec 23 '22 19:12

EVARATE


1 Answers

It seems that your implementation of std::cout writes to the C output stream stdout. And stdout is by default (when connected to a terminal) line-buffered.

Line-buffering means that output is buffered internally, until a newline ('\n') is added to the buffer. Then the buffer is flushed and actually written to the terminal.


You can explicitly flush the buffer by using the C++ I/O manipulator std::flush, as in

cout << "tick" << std::flush;

That will immediately flush the buffer and write it to the terminal. But without a newline. To add a newline you could use std::endl:

cout << "tick" << std::endl;  // Add newline and flush

But note that the explicit extra flush isn't needed here, as the newline itself flushes the buffer. Using std::endl will therefore first flush the buffer once because of the newline, and then flush the empty buffer because of the explicit flushing semantics.

It's recommended that you don't use std::flush (or std::endl) unless you really have to. In most cases it's not really needed.

like image 156
Some programmer dude Avatar answered Dec 25 '22 22:12

Some programmer dude