C++ Linked List - Reading data from a file with a sentinel

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2012-10-30T22:46:24Z Indexed on 2012/10/30 23:00 UTC
Read the original article Hit count: 238

Filed under:
|
|
|
|

So I've done quite a bit of research on this and can't get my output to work correctly. I need to read in data from a file and have it stored into a Linked List. The while loop used should stop once it hits the $$$$$ sentinel. Then I am to display the data (by searching by ID Number[user input]) I am not that far yet I just want to properly display the data and get it read in for right now.

My problem is when it displays the data is isn't stopping at the $$$$$ (even if I do "inFile.peek() != EOF and omit the $$$$$) I am still getting an extra garbage record.

I know it has something to do with my while loop and how I am creating a new Node but I can't get it to work any other way.

Any help would be appreciated.

students.txt

Nick J Cooley
324123
60
70
80
90
Jay M Hill
412254
70
80
90
100
$$$$$

assign6.h file

#pragma once
#include <iostream>
#include <string>
using namespace std;
class assign6
{
public:
    assign6(); // constructor
    void displayStudents();


private:
struct Node
{ string firstName; 
  string midIni;    
  string lastName;
  int idNum;
  int sco1; //Test score 1
  int sco2; //Test score 2
  int sco3; //Test score 3
  int sco4; //Test score 4
   Node *next;
};
Node *head;
Node *headPtr;


};

assign6Imp.cpp // Implementation File

#include "assign6.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

assign6::assign6() //constructor
{

ifstream inFile;
inFile.open("students.txt");

head = NULL;
head = new Node;
headPtr = head;
while (inFile.peek() != EOF) //reading in from file and storing in linked list
{

    inFile >> head->firstName >> head->midIni >> head->lastName;
    inFile >> head->idNum;
    inFile >> head->sco1;
    inFile >> head->sco2;
    inFile >> head->sco3;
    inFile >> head->sco4;

    if (inFile != "$$$$$")
    {
    head->next = NULL;
    head->next = new Node;
    head = head->next;
    }
}

head->next = NULL;

inFile.close();
}

void assign6::displayStudents()
{
int average = 0;
for (Node *cur = headPtr; cur != NULL; cur = cur->next)
{
    cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl;
    cout << cur->idNum << endl;
    average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4;
    cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl;
}
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about oop