cpp中的Flush函数
Flush function in cpp
我已经在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 updatedn";
fp.seekg(0);
while(fp.read((char *)&p,sizeof(p))) {
p.display();
}
fp.close();
return 0;
}
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 updatedn";
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.
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 重写std::ostream flush()函数,不被std::flush调用
- cpp中的Flush函数