Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 正在读取两次文本文件末尾的项_C++_File_Loops - Fatal编程技术网

C++ 正在读取两次文本文件末尾的项

C++ 正在读取两次文本文件末尾的项,c++,file,loops,C++,File,Loops,文本文件包含如下格式的行: lSdhmhlN 15479 6694.74 O szUfGnoI 18760 5275.53 n 我逐行读取文件,将其数据放入缓冲区变量中,将这些变量存储在TopicD对象中,然后将该对象插入到二叉搜索树中。问题是文件的最后一行被读取了两次,因此创建了两个相同的TopicD对象并插入到树中。为什么? 这是我的密码: template<class ItemType> void read( BinarySearchTree<I

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

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();
}
模板
无效读取(BinarySearchTree和tree)
{
ifstream读取(文件名.c_str());
if(read.fail())
die(“打开文件时出错”);
字符串strbuff;
双dubbuff;
int intbuff;
char chbuff;
而(!read.eof())
{
阅读>>strbuff;
阅读>>intbuff;
阅读>>dubbuff;
阅读>>chbuff;
TopicD buff(strbuff、dubbuff、intbuff、chbuff);
树。添加(buff);
}
read.close();
}

考虑从循环中剪掉一点:

while (read >> strbuff >> intbuff >> dubbuff >> chbuff)
    tree.add(TopicD( strbuff, dubbuff, intbuff, chbuff ));
当您达到eof时,切勿依赖
.eof()
为真。相反,当你一到那里就试图再次阅读时,这是真的。因此,到达EOF后的第一次读取失败,但到那时,您已经停止检查错误(顺便说一句,您从来没有检查过错误),只是盲目地将变量中的任何内容插入到树中