c++ - 调用 flush cout 无效

标签 c++ cout flush

我试图让 cout 缓冲区刷新,以便在我操作它之前查看一个字符串。我试图通过调用 std::flush()std::cout.flush() 来刷新缓冲区,但实际上都没有刷新我的输出。

只有调用 std::endl 才能为我成功刷新缓冲区。

这是我的代码

std::istringstream stm (game.date());
int day, month, year;
char delim = '/';

std::cout << "Date before: " << game.date() << std::flush; // first flush attempt
std::cout.flush();  // second flush attempt doesnt work
//std::cout << std::endl;   // if this is executed the buffer will flush

// Split date string into integers for comparison
stm >> month >> delim;
stm >> day >> delim;
stm >> year >> delim;

std::cout << "Date after: " << " | " << month << "/" << day << "/" << year << std::endl;

这是我的输出
日期之后: | 2013 年 1 月 31 日
日期之后: | 2012 年 3 月 21 日
日期之后: | 2011 年 11 月 11 日
日期之后: | 2010 年 10 月 1 日
日期之后: | 1/2/12

正如您所看到的,对 cout 的第一次调用从未被刷新,但正如我之前所说,缓冲区将成功地用调用刷新本身的 endl 刷新。我目前在运行 Mountain Lion 的主机 macbook pro 上运行带有 VirtualBox 的 Ubuntu 12.04。

我的 flush 调用是否有任何错误,或者这可能是系统问题?

最佳答案

两者都是 std::cout << flush;std::cout.flush();将冲洗 std::cout .

看起来您的代码在流中插入了一个回车符 ( \r )。假设您今年打印,您似乎将其作为 char 插入具有值(value) 13恰好是 \r .这样做的结果是您以后的输出将覆盖输出,因为它位于同一行。您可以通过在刷新流之前显式插入换行符 ( \n ) 来验证这一点。

关于c++ - 调用 flush cout 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483856/

相关文章:

c++ - 如何在 C++ 中创建良好的上下文类/返回引用?

c++ - 学c++之前需要先学c吗?

c++ - if 语句中有 float 的奇怪错误

c++ - 是否可以同时在两个对象上使用插入运算符?

java - FlushMode.AUTO后面检查了什么?

c++ - 仅手动冲洗 cout

c++ - 如何在多个文件之间创建一个全局变量?

c++ - 在头文件中隐藏非成员函数

c++ - Struct Char 数组中的奇怪行为

C++ GDI+ 清除上一个屏幕