cpp中的刷新函数

Flush function in cpp

我查阅了C++中flush函数的定义,得到了一些非常满意的答案,但是我最近遇到了下面的代码,我似乎无法理解使用flush是否使这里有很大的不同,即使不使用刷新,代码似乎也提供了有效的输出。请大家帮忙!

#include <iostream>
using namespace std;

class person {
public:
    int ph_no;
    char name[50];
    void accept() {
        cout<<"\nEnter name";
        cin>>name;
        cout<<"\nenter ph_no";
        cin>>ph_no;
    }
    void display() {
        cout<<"name:"<<name<<"\n";
        cout<<"phone_no:"<<ph_no<<"\n" ;
    }
};

int main() {
 // a few other functions to create file and read file &c &c.
   person p;
   int pno,pos,choice,offset,i;
   fstream fp;
   char name[20];

   cout<<"\n enter name";
   cin>>name;
   fp.open("d:\test.dat",ios::out|ios::in|ios::ate|ios::binary);
   fp.seekg(0,ios::beg);
   pos=-1;
   i=0;
   while(fp.read((char *)&p,sizeof(p))) {
      if((strcmp(name,p.name))==0) {
                           pos=i;
                           break;
      }
      i++;
   }
   offset=pos*sizeof(p);
   fp.seekp(offset);
   cout<<"\ncurrent phno:"<<p.ph_no;
   cout<<"\nenter new phone no";
   cin>>pno;
   p.ph_no=pno;
   fp.write((char *)&p,sizeof(p))<<flush;
   cout<<"\nrecord updated\n";
   fp.seekg(0);
   while(fp.read((char *)&p,sizeof(p))) {
                  p.display();
   }
   fp.close();
   return 0;
 }

std::coutstd::cintied

The tied stream is an output stream object which is flushed before each i/o operation in this stream object.

By default, the standard narrow streams cin and cerr are tied to cout, and their wide character counterparts (wcin and wcerr) to wcout. Library implementations may also tie clog and wclog.

至于:

fp.write((char *)&p,sizeof(p))<<flush;
cout<<"\nrecord updated\n";
fp.seekg(0);
// the next read will return the correct info even without the
// prev flush because:
// - either the seekg will force the flushing, if the seek-ed
//   position is outside the buffer range; *or*
// - the seekg pos is still inside the buffer, thus no 
//   I/O activity will be necessary to retrieve that info
while(fp.read((char *)&p,sizeof(p)))

Flush 强制任何缓冲输出实际输出到设备。为了性能,C++ 通常缓冲 IO。这意味着它将一些数据保存在内存中,并在与输出设备通信之前等待,直到它有更大的数量。每次您的 IO 速度快得多时,通过减少与设备进行大量数据通信的频率。

缓冲可能会导致交互情况下出现问题。如果您的用户提示位于缓冲区中而不显示给用户,用户可能会有点困惑。因此,当您需要确保实际显示最后的输出时,您可以使用 flush.