单链表输出额外字符

Single Linked List outputting extra character

本文关键字:字符 输出 链表 单链表      更新时间:2023-10-16

我写了一个程序,只输出一个链表,它运行得很好,但它输出最后一个字符两次(例如,如果要输出的单词是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;
	}
}

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

问题来了。EOF位仅在操作试图读取流的第一端并失败时设置。

在您的示例中,代码读取最后一个D,因为它读取了一个字符,所以它还没有遇到流的末尾,所以循环条件仍然成立。然后它尝试读取,发现流中没有字符,失败,设置eof和故障位,但为时已晚。执行循环体的其余部分,对digit中的任何值进行操作。简而言之:循环中的eof条件几乎总是错误的。

首选方式是循环输入操作:

while (infile >> digit)
{