c++文件操作 问什么是3个Date对象的数据,应该是2个啊解决方法
c++文件操作 问什么是3个Date对象的数据,应该是2个啊????
------解决方案--------------------
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
class Date
{
public:
Date(){};
Date(int y,int m,int d):year(y),month(m),day(d){};
int year;
int month;
int day;
};
void open_file(fstream &in,const string &filename)
{
in.close();
in.clear();
in.open(filename.c_str(),ios::in);
}
int main()
{
Date date1(2014,5,28),date2(2014,5,29);
fstream in;
string filename="1.txt";
fstream writefile(filename.c_str(),ios::out);
writefile.write((char*)(&date1),sizeof(Date));
writefile.write((char*)(&date2),sizeof(Date));
writefile.close();
writefile.clear();
open_file(in,filename);
Date date3;
while(!in.eof())
{
in.read((char*)(&date3),sizeof(Date));
cout<<date3.year<<date3.month<<date3.day<<endl;
}
return 0;
}
------解决方案--------------------
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。