would clog and cout in c++ behave differently in outputing the value?

188 Views Asked by At

I am expecting a similar behavior for Cout and Clog since both are buffered outputs. But when i am trying, it comes out different.

COUT:

int main()
{
    cout<<"Hello World" ;
    while(1);
    return 0;
}

Output: Nothing --> Since Cout is not flushed

CLOG:

int main()
{
    clog<<"Hello World" ;
    while(1);
    return 0;
}

Output: Hello World

Question: Both COUT and CLOG are buffered, so why not the output is same. How is "Hello World" being printed without the buffer being flushed

1

There are 1 best solutions below

0
On

First of all, I don't understand the purpose of the infinite loop. If you are trying to put the thread to sleep check this post StackOverflow post about thread sleeping in cpp,

Secondly, if you want to flush the stream use std::cout << std::flush;.

As for the difference between those: basically clog is a rarely used output stream similar to cerr. Basically clog outputs to stderr, similar to cerr, and not stdout. Checking these might help you understand the difference: COUT vs CERR vs CLOG, Tutorialspoint.

Now onto the difference between stdout and stderr. Stdout is always buffered and is flushed automatically at a convenient time or when requested explicitly to do so, meanwhile stderr is not fully buffered and always prints stuff immediately, without needing to be flushed explicitly.