单个链接列表输出额外字符

时间:2015-12-12 23:16:29

标签: c++

我编写了一个只输出单个链表的程序,它运行得很好,但它输出的是最后一个字符两次(例如,如果要输出的字是DAD则输出DADD)

#include <iostream>
#include <fstream>
using namespace std;
ifstream infile;
struct nodeType
{
	char num;
	nodeType *next;
};
int main()
{
	infile.open("TextFile2.txt");
	if (!infile)
		cout << "Cannot open the file." << endl;
	char digit;
	nodeType *head = NULL, *trail = NULL, *current = NULL;
	while (!infile.eof())
	{
		infile >> digit;
		if (head == NULL)
		{
			head = new nodeType;
			head->num = digit;
			head->next = NULL;
			trail = head;
		}
		else
		{
			current = new nodeType;
			current->num = digit;
			current->next = NULL;
			trail->next = current;
			trail = current;
		}

	}
	current = head;
	while (current != NULL)
	{
		cout << current->num;
		current = current->next;
	}
}

1 个答案:

答案 0 :(得分:1)

while (!infile.eof())
{
    infile >> digit;

这是问题所在。仅当操作尝试读取以读取流的末尾并且失败时才设置EOF位。

在你的例子中,代码读取最后的D,因为它读取单个字符,它还没有遇到流的结束,所以循环条件仍然是真的。然后它试图读取,发现流中没有字符,失败,设置eof和failbits,但为时已晚。执行循环体的其余部分,以digit中的任何值运行。简而言之: eof处于循环状态几乎总是错误的

优选的方法是循环输入操作:

while (infile >> digit)
{