Hello,
I am writing a program that reads in data from a text file and puts it into a linked list. Certain variables are read in only if the "officeHeld" number is a particular number, otherwise the variable is set to 0. When I run this through Visual Studio, I get a blank black screen with nothing on it. When I run it through our university's unix, I get "segmentation fault". I am not sure where the error is here and I'm at a loss. Any help or suggestion would be overwhelmingly appreciated. I'm attaching the code as well as some of the text file information!
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
ifstream inputFile;
struct PublicOfficial
{
string name;
string birthState;
int officeHeld;
int order;
int presFirstTerm;
int presLastTerm;
int viceFirstTerm;
int viceLastTerm;
PublicOfficial *next;
};
void LoadList(PublicOfficial *&head);
void addOfficial(PublicOfficial *&head, PublicOfficial *newNode);
void printOfficials(PublicOfficial *head);
int main()
{
PublicOfficial *head = NULL;
PublicOfficial *newNode = NULL;
LoadList(head);
printOfficials(head);
system("pause");
return 0;
}
void LoadList(PublicOfficial *&head)
{
PublicOfficial *newNode;
inputFile.open("officials.txt");
while (!inputFile.eof())
{
newNode = new PublicOfficial;
newNode->next = NULL;
getline(inputFile, newNode->name);
getline(inputFile, newNode->birthState);
inputFile >> newNode->officeHeld;
if (newNode->officeHeld == 1 || newNode ->officeHeld == 3)
{
inputFile >> newNode->order;
inputFile >> newNode->presFirstTerm;
inputFile >> newNode->presLastTerm;
}
else
{
newNode->order = 0;
newNode->presFirstTerm = 0;
newNode->presLastTerm = 0;
}
if(newNode->officeHeld == 2 || newNode-> officeHeld == 3)
{
inputFile >> newNode->viceFirstTerm;
inputFile >> newNode->viceLastTerm;
}
else
{
newNode->viceFirstTerm=0;
newNode->viceLastTerm=0;
}
addOfficial(head, newNode);
}
inputFile.close();
}
void addOfficial(PublicOfficial *&head, PublicOfficial *newNode)
{
if (!head)
{
head = newNode;
}
else
{
newNode->next = head;
head = newNode;
}
}
void printOfficials(PublicOfficial *head)
{
PublicOfficial *tptr = head;
if (!tptr)
{
cout << "The list is empty";
}
else{
while (tptr)
{
cout << setw(7) << tptr->birthState << setw(12) << tptr->officeHeld <<
setw(12) << tptr->order << setw(12) << tptr->presFirstTerm << setw(12)
<< tptr->presLastTerm << setw(12) << tptr->viceFirstTerm << setw(12) << tptr->viceLastTerm;
tptr= tptr->next;
}
}
cout << endl;
}
Here is a sample piece of the text document (it's a long one so I'm only including a sample, but if I can get it to read even one in, then it's working correctly)
Text File:
WALLACE, HENRY
IOWA
2
33
1941
1945
WASHINGTON, GEORGE
VIRGINIA
1
01
1789
1797
WHEELER, WILLIAM
NEW YORK
2
19
1877
1881
WILSON, HENRY
NEW HAMPSHIRE
2
18
1873
1877