【发布时间】:2023-03-15 02:55:02
【问题描述】:
我在将此文件中的数据存储和打印到我的链接列表中时遇到了一些问题。
文件信息:
Brown Aniya
Canaday Jordan
Germano Thomas
Grant Kiara
Gunathilaka Piyumi
Johnson Demetria
McGill Jayla
Mitchell Ty-Jaa'
Robertson Victoria
Taylor Chloe
Thomas Amon
Watkins Malkym
Wyatt Arkasia
这是当前的输出:
Brown Aniya
--------------------------------
Process exited after 0.1335 seconds with return value 0
Press any key to continue . . .
主要:
#include <iostream>
#include <fstream>
#include "P4-linkedList_Cox.h"
using namespace std;
int main()
{
tests oh;
oh.getNames();
oh.print();
return 0;
}
实施:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include "P4-linkedList_Cox.h"
using namespace std;
void tests::getNames()
{
ifstream inData;
inData.open("infile.dat");
nameType *newNode, *nodePtr;
newNode = new nameType;
newNode->link= NULL;
string um;
getline(inData, um);
newNode->info = um;
if (head != NULL)
{
nodePtr = head;
while (nodePtr->link)
{
nodePtr = nodePtr->link;
}
nodePtr->link = newNode;
}
else
head = newNode;
}
void tests::print()
{
nameType *nodePtr;
nodePtr = head;
while (nodePtr != NULL)
{
cout << nodePtr->info << endl;
nodePtr = nodePtr->link;
}
}
tests::tests()
{
head = NULL;
}
和.h:
using namespace std;
class tests
{
public:
void getNames();
void print();
tests();
private:
struct nameType
{
string info;
nameType *link;
};
nameType *head;
};
链接列表对我来说仍然很困惑,所以欢迎任何帮助!我在这篇文章中还需要更多的文字,但我想我已经很清楚地解释了我的问题。我只需要帮助将 .dat 文件中的所有名称存储到我的链接列表中,然后输出该列表。
【问题讨论】:
-
您的
getNames只读取一行,因此链表不能包含多个名称。
标签: c++ linked-list load-data-infile