Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图了解刷新缓冲区问题的效果 我是C++初学者,所以如果我的问题听起来很愚蠢或者什么的话,我深感抱歉。_C++_C++11_Buffer - Fatal编程技术网

试图了解刷新缓冲区问题的效果 我是C++初学者,所以如果我的问题听起来很愚蠢或者什么的话,我深感抱歉。

试图了解刷新缓冲区问题的效果 我是C++初学者,所以如果我的问题听起来很愚蠢或者什么的话,我深感抱歉。,c++,c++11,buffer,C++,C++11,Buffer,我一直在读一本书,书中简单介绍了流缓冲区,在某些情况下刷新缓冲区很重要,因此为了理解效果,我运行了以下代码: 代码1: #include <iostream> #include <thread> #include <chrono> using namespace std; int main() { for (int i = 1; i <= 5; ++i) { cout << i << &qu

我一直在读一本书,书中简单介绍了流缓冲区,在某些情况下刷新缓冲区很重要,因此为了理解效果,我运行了以下代码:

代码1:

#include <iostream>
#include <thread>
#include <chrono>   
using namespace std;
      
int main()
{
  for (int i = 1; i <= 5; ++i)
  {
      cout << i << " ";
      this_thread::sleep_for(chrono::seconds(1));
  }
  cout << endl;
  return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{

对于(int i=1;i这里是一个有异常刷新和无异常刷新的示例(该异常应在刷新最后一行之前终止程序):


但没有提到“没有冲洗的测试”,因为程序在自动刷新之前就结束了。

尝试从命令行运行编译后的非
flush
ing程序。如果从IDE中运行它,它可能会自动刷新缓冲区。例如,如果我在linux bash shell中运行它,它会等待5秒钟,然后立即打印所有五个数字。
cout
输出通常是缓冲的,但不是必需的。本书描述的两种行为是大多数实现中的典型行为,当
cout
是行缓冲时,这意味着直到打印换行符(或缓冲区填满)时缓冲区才会刷新.
std::endl
std::flush
都强制立即刷新,这如何解释为什么OP没有看到代码1和代码2的任何差异?根据OP所说,OP使用的环境可能实际显示
测试而没有刷新
。这是真的。我的想法是使用相同的godbolt配置应该会产生相同的输出-休眠的东西在那里不起作用,因为它一次推送所有的输出
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

int main()
{
   for (int i = 1; i <= 5; ++i)
   {
      cout << i << " " << flush;
      this_thread::sleep_for(chrono::seconds(1));
   }
   return 0;
}
#include <iostream>
int main() {
    std::cout << "test with flush" << std::flush;
    std::cout << "test without flush";
    throw;
}
Program returned: 139
terminate called without an active exception
test with flush