Strange behaviour of std::cout in Linux

孤人 提交于 2019-12-02 04:52:32

std::cout is an stream, and it is buffered. You can flush it by several ways:

std::cout.flush();

std::cout << std::flush;

std::cout << std::endl;  // same as:  std::cout << "\n" << std::flush`


johny:

I am flushing the buffer before the cycle using std::endl. The problem arises when printing dot representing % of processed data inside the cycle.

If you flush the buffer before the cycle, that does not affect the output in the cycle. You have to flush in or after the cycle, to see the output.

If you don't flush your output, your output is not guaranteed to be visible outside your program. The fact that it is not printing in your terminal is just a consequence of the default behavior in linux to do line buffering when the output is a tty. If you run your program on linux with its output piped to another thing, like

 ./your_program | cat

Then the default buffer will be MUCH larger, most likely it will be at least 4096 bytes. So nothing will get displayed until the big buffer gets full. but really, the behaviour is OS specific unless you flush std::cout yourself.

To flush std::cout, use :

std::cout << std::flush;

also, using

std::cout << std::endl;

is a shortcut to

std::cout << '\n' << std::flush;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!