📜  C++中的缓冲区刷新意味着什么?

📅  最后修改于: 2021-05-30 09:04:52             🧑  作者: Mango

缓冲区刷新是将计算机数据从临时存储区传输到计算机的永久内存。例如,如果我们在文件中进行任何更改,则我们在一台计算机屏幕上看到的更改将被临时存储在缓冲区中。
通常,当我们打开任何Word文档时,都会出现一个临时文件,而当您关闭主文件时,该文件会自动销毁。因此,当我们保存工作时,自上次保存文档以来对文档所做的更改将从缓冲区刷新到硬盘上的永久存储。

在C++中,我们可以显式刷新以强制写入缓冲区。一般标准:: ENDL函数的工作原理相同通过插入字符并刷新流。 stdout / cout是行缓冲的,这是在您编写换行符或显式刷新缓冲区之前,输出不会发送到OS。例如,

// Causes only one write to underlying file 
// instead of 5, which is much better for 
// performance.
std::cout << a << " + " << b << " = " << std::endl;

但是有某些缺点,例如

// Below is C++ program
#include 
#include 
#include 
  
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;
}
The above program will output 1 2 3 4 5 at once.

因此,在这种情况下,将使用附加的“刷新”函数来确保根据我们的要求显示输出。例如,

// C++ program to demonstrate the 
// use of flush function
#include 
#include 
#include 
using namespace std;
int main()
{
   for (int i = 1; i <= 5; ++i)
   {
      cout << i << " " << flush;
      this_thread::sleep_for(chrono::seconds(1));
   }
   return 0;
}
The above program will program will print the 
numbers(1 2 3 4 5) one by one rather than once. 
The reason is flush function flushed the output 
to the file/terminal instantly.

笔记:

  1. 您无法在在线编译器上运行该程序以查看其区别,因为它们仅在终止时才提供输出。因此,您需要在离线编译器(例如gcc或clang)中运行所有上述程序。
  2. 读cin会冲洗cout,因此我们不需要显式冲洗即可。

参考:

  • http://searchstorage.techtarget.com/definition/buffer-flush
  • https://stackoverflow.com/questions/15042849/what-does-flushing-the-buffer-mean

相关文章:
在C中使用fflush(stdin)

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”