0

I wrote a program to just output a single linked list and it works just fine, however it is outputting the last character twice (ex if the word to be outputted is DAD it outputs 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 Answers1

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

Here is the problem. EOF bit is set only when operation tried to read to read past th end of stream and failed.

In your example, code reads last D, as it read a single character, it did not encountered the end of stream yet, so loop condition is still true. Then it tries to read, finds out that there is no characters in stream, fails, sets eof and failbits, but it is too late. The rest of loop body is executed, operating on whatever value is in digit. In short: eof in loop condition is almost always wrong.

Preferable way is to loop on input operation:

while (infile >> digit)
{
Revolver_Ocelot
  • 7,747
  • 3
  • 26
  • 45