单链表输出额外字符
Single Linked List outputting extra character
我写了一个程序,只输出一个链表,它运行得很好,但它输出最后一个字符两次(例如,如果要输出的单词是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)
{
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 字符的输入/输出操作
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- C++输出奇怪的字符而不是数字 (Windows)
- 如何存储 unicode 字符并将其输出到文件?
- C++中附加的字符*的奇怪输出
- 来自无符号字符缓冲区的虚拟输出
- 将未签名的字符写入输出文件
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 如何在C++中正确地将我的语言字符输出到HTML文件中
- x86 上的指针大小和奇怪的字符输出
- 如何修复C++中的随机字符输出?
- Visual Studio-怪异的字符输出
- 需要我当前的字符输出,这是它在C++中的整数值
- 宽字符输出结果
- 将字符输出随机化为文本文件
- C++和printf-奇怪的字符输出
- 显示无符号字符*和有符号字符*输出的结果是否完全相同
- 下一个回文 .奇怪的字符输出
- 不要将宽字符输出到命令提示符