【发布时间】:2016-04-21 01:10:35
【问题描述】:
我刚开始学习链表,我正在尝试从文件中提取某些信息并使用推送功能将其插入到链表中。当我尝试查看信息以查看它是否正确插入时,它只会一遍又一遍地显示信息的最后一行。我究竟做错了什么?这是我的代码:
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;
}
}
【问题讨论】:
标签: c++ struct linked-list