Why does my cout output not appear immediately?

前端 未结 2 950
南笙
南笙 2020-12-03 21:44

it does not print the string put in the loop. The program was written with the help of G++, with sys/types.h header file included

for(int i=0;i<9;i++)
{
          


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 22:42

    What you're likely seeing here is an effect of the output being buffered. In general the output won't actually be written until std::endl is used.

    for(int i=0;i<9;i++)
    {
        // Flushes and adds a newline
        cout<< "||" << endl;
        sleep(1);
    }
    

    Under the hood std::endl is adding a newline character and then using std::flush to force the output to the console. You can use std::flush directly to get the same effect

    for(int i=0;i<9;i++)
    {
        cout << "||" << flush;
        sleep(1);
    }
    

提交回复
热议问题