遇到的问题
在写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;
}
在使用C++ Primer Plus练习二进制文件输入时,遇到ifstream.read()导致的循环次数异常问题。原本预期只循环一次,但实际循环了两次。原因是第一次读取文件后,文件指针并未到达EOF,于是在第二次循环中继续读取。解决方案是修改条件判断,确保在读取前检查文件是否已到末尾。
529

被折叠的 条评论
为什么被折叠?



