I'm working on a program that is supposed to read the contents of a file into a linked list in order to create a "hypercard stack" (I've listed the specifics here).
I know there's a list Class in the C++ standard library, but since I've never worked with the standard library before, I have no idea how to make it work with this particular problem.
Here is the code I've managed to come up with so far through piecing together bits and pieces of online tutorials I've come across.
My .h file:
//program6.h
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;
class Node {
public:
Node();
Node(char code, int num, string data);
Node(Node & node);
~Node();
bool readFile();
void setNext(Node* next);
void print();
private:
char Code;
int Num;
string Data;
Node *Next;
};
My Implementation File:
//program6.cpp
#include "program6.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
Node::Node() {
Code = '\0';
Num = 0;
Data = "";
Next = NULL;
}
Node::Node(char code, int num, string data) {
Code = code;
Num = num;
Data = data;
Next = NULL;
}
Node::Node(Node & node) {
Code = node.Code;
Num = node.Num;
Data = node.Data;
Next = NULL;
}
Node::~Node() {
}
bool Node::readFile() {
char code = '\0';
int num = 0;
string data = "";
ifstream inputFile;
inputFile.open("prog6.dat");
if(!inputFile) {
cerr << "Open Faiulre" << endl;
exit(1);
return false;
}
Node *head = NULL;
while(!inputFile.eof()) {
inputFile >> code >> num >> data;
Node *temp = new Node(code, num, data);
temp->setNext(head);
head = temp;
}
inputFile.close();
head->print();
return true;
}
void Node::setNext(Node* next) {
Next = next;
}
void Node::print() {
cout << Code << " " << Num << " " << Data;
if(Next != NULL)
Next->print();
}
And my main/test file:
//program6test.cpp
#include "program6.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
int main() {
Node list;
if(list.readFile())
cout << "Success" << endl;
else
cout << "Failure" << endl;
return 0;
}
And here is teh file I need to read:
i 27 Mary had a little lamb
i 15 Today is a good day
i 35 Now is the time!
i 9 This lab is easy and fun
p
d 35
t
i 37 Better Now.
f
p
h
p
d 27
d 15
d 37
d 9
i 44 This should be it!
t
p
Update Thanks to the answer below, I was able to get rid of the "undefined reference" errors I was getting initially, however, here is the error I'm getting when I run the program now.
terminate called after throwing an instance of 'St9bad_alloc'
what(): St9bad_alloc
Aborted
Also please keep in mind that while I am getting an error that needs to be resolved, that isn't the primary purpose of this question.
I'm sorry if this is really broad, I don't really understand any of this so don't really know how to narrow it down any further. Can anyone help me figure out how to use the list Class to solve this problem, again, the specifics of the program can be found at the link I provided earlier in the post.