我无法从文件中读取链接列表。我有一种(可能非常低效的方式)读取文件并将每个节点加载到链表中,但是如果我读取并尝试打印多行,那么打印时会出现无限循环。
加载代码
void readFile()
{
string text;
string temp; // Added this line
node* newNode = new node;
ifstream file;
file.open("example.txt");
for (int i = 0; i < 1; i++)
{
getline(file, temp);
text = temp;
string input = text;
istringstream ss(input);
string token;
int counter = 0;
while (getline(ss, token, ','))
{
cout << token << '\n';
newNode->rented = token;
counter++;
if (counter == 0)
{
newNode->rented = token;
}
else if (counter == 1)
{
std::istringstream ss(token);
ss >> newNode->maxload;
}
else if (counter == 2)
{
std::istringstream ss(token);
ss >> newNode->passengers;
}
else if (counter == 3)
{
std::istringstream ss(token);
ss >> newNode->doors;
}
else if (counter == 4)
{
newNode->registration = token;
}
else if (counter == 5)
{
std::istringstream ss(token);
ss >> newNode->engine;
}
else if (counter == 6)
{
newNode->model = token;
}
else if (counter == 7)
{
newNode->make = token;
}
}
system("pause");
list.insertNode(newNode);
}
file.close();
}
插入节点
void linkedList::insertNode(node* newNode)
{
newNode->nextNode = head;
head = newNode;
}
打印代码
void linkedList::displayList()
{
node* thisNode = head;
if (head == NULL)
{
cout << "The list is empty\n";
return;
}
else
cout << "---------------------------------------------------------\n";
cout << "\tMake\tReg Number\tRented\n";
cout << "---------------------------------------------------------\n";
cout << "\t";
do
{
cout << setw(8) << left << thisNode->make;
cout << setw(16) << left << thisNode->registration;
cout << setw(10) << left << thisNode->rented;
cout << "\n\t";
thisNode = thisNode->nextNode;
} while (thisNode != NULL);
{
cout << "\n\n";
}
}
文字档案
car,Ferarri,12.0,aa,3,1,0,true
car,Mercedes,12.0,bb,5,4,0,false
car,Ford,1.6,cc,5,4,0,false
如果我将加载代码中的for循环设置为1次迭代,则输出正确的显示:
0 aa true
但是,如果我将for循环设置为迭代次数超过1次,则打印代码将无限打印最后一行读取的内容(忽略它之前的所有行)?
0 bb false
0 bb false
0 bb false
...
任何人都可以看到为什么会这样做吗?
答案 0 :(得分:2)
您只是分配一个节点。将以下行移动到for循环的开头:
node* newNode = new node;
否则,每次都会覆盖节点中的所有内容,然后将其重复添加到列表中,从而创建循环引用。