When must the output stream in C++ be flushed?

后端 未结 6 1152
执笔经年
执笔经年 2021-01-21 21:45

I understand cout << \'\\n\' is preferred over cout << endl; but cout << \'\\n\' doesn\'t flush the output stream. When

6条回答
  •  Happy的楠姐
    2021-01-21 22:21

    Flushing can be disastrous if you are writing a large file with frequent spaces.

    For example

    for(int i = 0 ;i < LARGENUMBER;i++)
    {//Slow?
      auto point = xyz[i];
      cout<< point.x <<",",point.y<

    vs

    for(int i = 0 ;i < LARGENUMBER;i++)
    {//faster
      auto point = xyz[i];
      cout<< point.x <<",",point.y<<"\n";
    }
    

    vs

    for(int i = 0 ;i < LARGENUMBER;i++)
    {//fastest?
      auto point = xyz[i];
      printf("%i,%i\n",point.x,point.y);
    }
    

    endl() was often know for doing other things, for example synchronize threads when in a so-called debug mode on MSVC, resulting in multithreaded programs that, contrary to expectation, printed uninterrupted phrases from different threads.

提交回复
热议问题