【问题标题】:Flush function in cppcpp中的flush函数
【发布时间】:2016-10-13 06:00:40
【问题描述】:

我在 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;
 }

【问题讨论】:

  • 您认为flush 会在哪里发挥作用?
  • fstream::write 返回basic_ostream&amp;,所以应该没问题,尽管为了清楚起见我会在下一行中调用它。

标签: c++ fstream flush


【解决方案1】:

std::cout 和 std::cin 是 tied

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

默认情况下,标准窄流cin 和cerr 绑定到cout,它们的宽字符对应物(wcin 和wcerr)绑定到wcout。库实现也可以绑定clog 和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)))

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 非常感谢您的回答!现在似乎更有意义了!! :D :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多