c++ - 单链表输出额外字符

标签 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;
	}
}

最佳答案

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

问题来了。 EOF 位仅在操作尝试读取以读取超过流的末尾但失败时设置。

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

更好的方法是循环输入操作:

while (infile >> digit)
{

关于c++ - 单链表输出额外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246135/

相关文章:

c++ - 创建进程间共享的全局命名计数器

c++ - 搜索数组的上限

c++ - 将带有 automake 的预构建二进制文件放在哪里?

c++ - 将对象插入队列

c++ - 在 OpenCV 中将两张纸片合并成一张图像

c++ - 编译的Elf二进制文件太大

c++ - 调用C++对象析构函数的多种方式

c++ - 使用 Boost TTI 检查类型是否具有成员函数(还有继承成员函数)

c++ - 如何以编程方式获取进程使用的内存量?

c++ - 数据压缩算法