Why does my cout output not appear immediately?

前端 未结 2 941
南笙
南笙 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:19

    You're not flushing your output.

    std::cout << "||" << std::flush;
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题