您的位置:首页 > 其它

ifstream.read()的一个问题

2015-06-25 22:39 162 查看

遇到的问题

在写C++ Primer Plus里的一个练习题时,遇到一个问题。原题目就不写了,来看看主要的问题:

//定义一个结构
struct test
{
char name[4];
};

//声明一个test结构temp,然后赋值
struct test temp;
cin.getline(temp.name, 4);

//使用ofstream.write()方法写入dat_test.dat文件中
ofstream fout("dat_test.dat", ios_base::out | ios_base::binary);
fout.write((char *)&temp, sizeof(test));
fout.close();

//************主要问题出现在下面的代码中************

ifstream fin("dat_test.dat", ios_base::in | ios_base::binary);

//使用ifstream.read()方法读取dat_test.dat文件中的内容
while(!fin.eof())           // <==就是这里
{
struct test temp;
fin.read((char *)&temp, sizeof(test));
cout<<"姓名:"<<temp.name<<endl;
}


本以为只进行一次循环

然而:



竟然循环了两次!!!

原因

测试了几次后发现问题所在

while(!fin.eof())          //标记1
{
struct test temp;
fin.read((char *)&temp, sizeof(test));
cout<<"姓名:"<<temp.name<<endl;
}


在标记1处,在还没有
read()
之前判断了
fin


刚进入循环,
!fin.eof()
true
,然后
read()


第二次循环,
!fin.eof()
依旧是
true
,因为上一次的
read()
只是读了大小为
sizeof(struct test)
的文件区块,还没有读到EOF。

第三次循环时,
!fin.eof()
false


解决方法

更改后的
while
如下:

//第一种改法:
while (fin.peek() != EOF)
{
struct test temp;
fin.read((char *)&temp, sizeof(test));
cout << "姓名:" << temp.name << endl;
}

//第二种改法
struct test temp;
while (fin.read((char *)&temp, sizeof(test)))
{
cout << "姓名:" << temp.name << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: