【发布时间】: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&,所以应该没问题,尽管为了清楚起见我会在下一行中调用它。