cpp中的刷新功能

时间:2016-10-13 06:00:40

标签: c++ fstream flush

我在C ++中查找了函数flush的定义,我得到了一些非常令人满意的答案,但我最近遇到了以下代码,我似乎无法理解如果使用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;
 }

2 个答案:

答案 0 :(得分:2)

std::coutstd::cintied

  

绑定流是一个输出流对象,在this流对象中的每个i / o操作之前刷新。

     

默认情况下,标准窄流cincerr与cout相关联,其广泛字符对应(wcinwcerr)与wcout相关联。图书馆实施也可以绑定clogwclog

至于:

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)))

答案 1 :(得分:0)

Flush强制任何缓冲输出实际输出到设备。为了提高性能,C ++通常会缓冲IO。这意味着它会将一些数据保留在内存中,并等到它与输出设备通信之前有更大的数量。每次IO更快时,通过较少的数据与设备交谈。

缓冲可能会在交互情况下导致问题。如果您的用户提示符位于缓冲区中而未显示给用户,则用户可能会有点困惑。因此,当您需要确定实际显示的是上一个输出时,请使用flush。

相关问题