I think this has happened to me before. This isA3.txt:
%INSERT
MARK 29
DAVID 21
JOHN 44
JOHN 51
LARRY 39
MARK 21
DAVID 18
JOHN 28
MARK 35
DONALD 41
PHIL 26
Even though I use sourcefile >> reader at the end of the loop, the program keeps outputting "reader: MARK", meaning the sourcefile >> reader; statement isn’t working (i.e., it keeps getting the same input over and over again, or it’s not getting any input).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct data
{
string name;
int id;
data* link;
};
data* start;
data* node;
ifstream sourcefile;
int main()
{
data* start = new data;
start -> link = NULL;
string input;
string reader;
sourcefile.open("A3.txt");
bool firstnode = true;
sourcefile >> input;
node = start;
cout << "Recieved command: " << input << endl;
if(input == "%INSERT")
{
// unlike the other ones, this function keeps reading until it hits another command
sourcefile >> reader;
cout << "Insert name: " << reader << endl;
// iterates through the link list until it hits the final node
while(node -> link != NULL)
node = node -> link;
while(reader[0] != '%')
{
if(firstnode)
start -> link = new data;
else
node -> link = new data;
sourcefile >> node -> name;
sourcefile >> node -> id;
node -> link = NULL;
sourcefile >> reader;
cout << "reader: " << reader << endl;
}
}
else
return 0;
}
Also… offtopic. The compiler said that switch statements can’t be used with strings, is that really true, or was I doing something else wrong?
sourcefile >> node -> id;fails, and after that none of the input operations fromsourcefilesucceed, asfailbitbecomes set in thesourcefilestream.sourcefile >> node -> id;fails because it tries to read an integer but encounters “DAVID” in the stream. That happens becausesourcefile >> reader;consumes “MARK”,sourcefile >> node -> name;consumes “29”, sosourcefile >> node -> id;is then left with “DAVID”. Try replacingsourcefile >> node -> name;withnode -> name = reader.And yes, you can’t use strings in
switch, only integral and enumeration expressions.On another offtopic note, you don’t seem to release the memory allocated for nodes (easy solution: just use
std::list).EDIT: Here’s how your program might look like when if you used
std::list: