调用冲洗指令无效 [英] Calls to flush cout are ineffective

查看:90
本文介绍了调用冲洗指令无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清空cout缓冲区以查看字符串,然后再对其进行操作。我尝试通过调用 std :: flush() std :: cout.flush()但实际上都没有刷新我的输出。

I am attempting to have the cout buffer flush to view a string before I manipulate it. Ive attempted to flush the buffer with calls to both std::flush() and std::cout.flush() but neither actually flush my output.

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

Only a call to std::endl has successfully flushed the buffer for me.

这是我的代码

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;

这是我的输出

以后的日期: 13/1/31

日期:| | 12/3/21

之后的日期:| 11/11/11

之后的日期:| 10/1/10

日期:| | 1/2/12

因此您可以看到对cout的首次调用从未刷新过,但是正如我之前所说,在缓冲区将成功使用endl刷新后,调用本身会刷新。我当前在运行Mountain Lion的主机Macbook Pro上运行带有VirtualBox的Ubuntu 12.04。

So as you can see the first call to cout isnt ever flushed but as I said before the buffer will successfully flush with endl, which calls flush itself. I am currently running Ubuntu 12.04 with VirtualBox on my host macbook pro running Mountain Lion.

在冲洗呼叫中我可能做错了什么吗,或者这可能是系统问题?

Is there anything I may be doing wrong in my flush calls or is this potentially a system issue?

推荐答案

两者 std :: cout<< flush; std :: cout.flush(); 将刷新 std :: cout

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

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.

这篇关于调用冲洗指令无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆