Calls to flush cout are ineffective

≡放荡痞女 提交于 2019-12-05 04:17:46

Both std::cout << flush; and std::cout.flush(); will flush std::cout.

It looks as if your code inserts a carriage return (\r) into the stream. Assuming you print this year, it seems you insert it as a char with value 13 which happens to be \r. The upshot of this is that your later output will just overwrite the output as it will be on the same line. You can verify this by explicitly inserting a newline (\n) before flushing the stream.

There's a system buffer on cout that will still buffer your output in modern Linux systems.

To disable it for a run of your program use the command stdbuf like this:

stdbuf -o 0 ./yourprogram --yourparams

If you need to disable the buffering in the debugger, use it like this:

stdbuf -o 0 gdb --args ./yourprogram --yourparams

Flush only writes the buffers for the stream to the actual device (file or tty).

It doesn't move to the next line, if that's what you expect.

This is by design.

Note, here's a cleaner version of the code, that appears to work as advertised (with or without the flush, for that matter):

See it Live on Coliru

#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>

struct Game { 
    std::string _date;
    std::string date() const { return _date; }
};

int main()
{
    for (Game game : std::vector<Game> { {"01/02/1999"}, {"24/10/2013"}})
    {
        std::istringstream stm (game.date());
        int day, month, year;
        char delim = '/';

        std::cout << "Date before: " << game.date();

        stm >> month >> delim;
        assert(stm && '/' == delim);

        stm >> day >> delim;
        assert(stm && '/' == delim);

        stm >> year;

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