【发布时间】:2016-04-21 18:27:04
【问题描述】:
我的程序的第一部分是从文件中提取特定数据并将其插入到链表中。我成功地创建了程序的那一部分,但我在搜索我的链接列表和打印数据时遇到了困难。到目前为止,这是我的代码:
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node *next;
};
Node *world;
void makeList(Node *&world);
void printCountry (Node *&world, string name);
int main ()
{
string name;
makeList(world);
printCountry (world, name);
return 0;
}
void makeList(Node *world)
{
ifstream inFile("population.csv");
if (!inFile.fail())
{
cout << "File has opened successfully." << endl;
}
else
{
cout << "File has failed to open." << endl;
exit(1);
}
double temp, temp1, temp2, temp3, population;
string countryName;
Node *top = new Node;
world = top;
while (!inFile.eof())
{
top -> next = NULL;
inFile >> temp >> temp1 >> temp2 >> temp3 >> population;
getline (inFile, countryName);
top -> ctry.population = population;
top -> ctry.name = countryName;
if (!inFile.eof())
{
top -> next = new Node;
top = top -> next;
}
}
// check if list is created successfully
while (world -> next != NULL)
{
cout << world -> ctry.population << " " << world -> ctry.name << endl;
world = world -> next;
}
}
void printCountry (Node *world, string name)
{
string countryToFind;
cout << "What country do you want to find? " << endl;
cin >> countryToFind;
while (world != NULL)
{
if (world -> ctry.name == countryToFind)
{
cout << "Country has been found: " << world -> ctry.name << " has a population of "
<< world -> ctry.population << endl;
break;
}
else
{
if (world -> next == NULL)
{
cout << "End of file" << endl;
break;
}
world = world -> next;
}
}
}
当我运行 printCountry 时,它只是搜索列表并打印文件结尾。我在 printCountry 做错了什么?
【问题讨论】:
-
如果您要发布代码,请尝试将其设为您的真实代码。 (复制/粘贴是当天的顺序)。例如:您将
makeList声明为void makeList(Node *& world),但实现没有引用,只有一个指针类型:void makeList(Node *world)。printCountry也是如此。这将编译,但无法按原样链接。 -
void makeList(Node *&world);这行之后我没有继续阅读,因为我不明白。为什么要用这么奇怪的参数类型? -
@tobi303 目的是通过引用更改头指针。如果实际实施的话,它会起作用。
-
@WhozCraig 哦,我明白了。感谢您的澄清。乍一看有点迷茫
标签: c++ struct linked-list ifstream