文本文件末尾的项被读取两次
Item at end of text file being read twice
文本文件包含如下格式的行:
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后的第一次读取是失败的,但到那时您已经停止检查错误(顺便说一下,您从未开始检查),只是盲目地将变量中的任何内容插入到树中。
相关文章:
- C++两次从文件保存对象读取多重继承
- std::getline 读取最后一个字符串两次
- 使用字符串流逐行读取文件两次
- C OOP,读取文件的问题,EOF使用了两次,排行榜
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量
- 符号从 ifstream 读取两次
- 一次读取两个字节的.dat文件
- 两次读取指针就是给出垃圾值
- 正在从文件中读取最后两次出现的内容
- 流>>读取最后一行两次
- C++ - 函数在尝试忽略同一行时读取同一行两次
- 在同一 unix 套接字连接中读取元素两次时出错
- 函数读取输入并运行函数两次
- QXmlStreamReader.readNextStartElement()读取开始元素两次
- 两次读取std::cin的输入
- 如何从字符串流中的同一位置读取两次
- C/C++如何在回车后从stdin中读取,连续命中两次或在两个换行后
- 从输入中读取单词序列。使用"Quit"终止,按输入顺序打印,不要打印两次单词。
- 如何在一行中读取相同的文件两次
- 连续两次读取套接字,第二次读取不起作用