I just started learning about linked list and I'm trying to extract certain info from a file and insert it into a linked list using a push function. When I try to view the info to see if it inserted correctly, it just displays the last line of the info over and over. What am I doing wrong? This is my code:
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node *next;
};
Node *world;
void push(Node *&world);
int main ()
{
push(world);
return 0;
}
void push(Node *&world)
{
ifstream inFile("file.csv");
if (!inFile.fail())
{
cout << "File has opened successfully." << endl;
}
if (inFile.fail())
{
cout << "File has failed to open." << endl;
exit(1);
}
double temp, temp1, temp2, temp3, population;
string countryName;
Node *top = new Node;
for (int i = 0; i < 300; i++)
{
if (inFile.eof())
{
top->next = NULL;
break;
}
inFile >> temp >> temp1 >> temp2 >> temp3 >> population;
getline (inFile,countryName);
top -> ctry.population = population;
top -> next = world;
world = top;
top -> ctry.name = countryName;
top -> next = world;
world = top;
}
for (int j = 0; j < 5; j++)
{
cout << top -> ctry.name << endl;
top -> next;
}
}