文本文件末尾的项被读取两次

Item at end of text file being read twice

本文关键字:两次 读取 文件 文本      更新时间:2023-10-16

文本文件包含如下格式的行:

lSdhmhlN   15479   6694.74   O
szUfGnoI   18760   5275.53   n

我正在逐行读取文件,将其数据放入缓冲区变量中,将这些变量存储在TopicD对象中,并将该对象插入二叉搜索树中。问题是文件的最后一行被读取了两次,因此创建了两个相同的TopicD对象并将其插入到树中。为什么?

下面是我的代码:

template<class ItemType>
void read( BinarySearchTree<ItemType> & tree )
{
ifstream read( FILE_NAME.c_str() );
if ( read.fail() )
    die( "Error opening the file." );
string strbuff;
double dubbuff;
int intbuff;
char chbuff;
while ( !read.eof() )
{
    read >> strbuff;
    read >> intbuff;
    read >> dubbuff;
    read >> chbuff;
    TopicD buff( strbuff, dubbuff, intbuff, chbuff );
    tree.add(buff);
}
read.close();
}

考虑从循环中剪掉一点:

while (read >> strbuff >> intbuff >> dubbuff >> chbuff)
    tree.add(TopicD( strbuff, dubbuff, intbuff, chbuff ));
达到 EOF时,永远不要依赖.eof()为真。更确切地说,当你在那里尝试再次阅读时,除了其他事情之外,它将是真实的。因此,到达EOF后的第一次读取是失败的,但到那时您已经停止检查错误(顺便说一下,您从未开始检查),只是盲目地将变量中的任何内容插入到树中。