I'm trying to write some code that will read numbers from one file and put those numbers into a list and then print the list in another file. I'm having trouble trying to get the numbers from the infile to read correctly. The program compiles ok but when the list is displayed it has the wrong numbers in it and I'm not sure where the numbers came from.
#include <iostream>
#include <fstream>
using namespace std;
// Singly-linked list node
class Link {
public:
int element; // Value for this node
Link *next; // Pointer to next node in list
Link(const int elemval, Link* nextval =NULL)
{ element = elemval; next = nextval; }
Link(Link* nextval =NULL) { next = nextval; }
};
class MyList {
private:
Link* head; // Pointer to list header
Link* tail; // Pointer to last int in list
Link* fence; // Last element on left side
int leftcnt; // Size of left partition
int rightcnt; // Size of right partition
// Initialization routine.
// note that it's inline.
void init() {
fence = tail = head = new Link;
leftcnt = rightcnt = 0;
}
public:
MyList(int size = 1000) { init(); }
bool insert(const int);
bool append(const int);
void print() const;
void next() {
if (fence != tail) // Don't move fence if right empty
{ fence = fence->next; rightcnt--; leftcnt++; }
}
};
int main() {
MyList L1;
char temp;
ifstream inStream;
ofstream outStream;
inStream.open("test.txt");
outStream.open("testout.txt");
if (inStream.fail()){
cout << "Input file opening failed.\n";
}
if (inStream.fail()){
cout << "Output file opening failed.\n";
}
inStream.get(temp);
while (!inStream.eof()) {
L1.insert(temp);
inStream >> temp;
}
L1.print();
inStream.close( );
outStream.close( );
cout << endl;
system("pause");
return 0;
}
bool MyList::insert(const int item) {
fence->next = new Link(item, fence->next);
if (tail == fence) tail = fence->next; // New tail
rightcnt++;
return true;
}
bool MyList::append(const int item) {
tail = tail->next = new Link(item, NULL);
rightcnt++;
return true;
}
void MyList::print() const {
Link* temp = head;
cout << temp->next->element << " ";
}
Right now I have it so it just print the code on the screen and it does not output to a file. Just trying to get the inStream working correctly. Any idea whats going on here??