2015-12-12 65 views
0

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

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

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

回答

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

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

在您的示例中,代码读取最后一个D,因为它读取单个字符,但它尚未遇到流结束,因此循环条件仍然为真。然后它尝试读取,发现流中没有字符,失败,设置eof和失败位,但是为时已晚。循环体的其余部分被执行,在digit的任何值上运行。总之:eof在循环条件下几乎总是错的

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

while (infile >> digit) 
{