我对指针和链表很新,但我正在尝试编写一个简单的程序,将文本文件中的数据读入链表。我输入功能有问题。它看起来像这样:
DVDNode* CreateList(string fileName)
{
ifstream inFile;
inFile.open(fileName.c_str());
DVDNode* head = NULL;
DVDNode* dvdPtr;
dvdPtr = new DVDNode;
while(inFile && dvdPtr != NULL)
{
getline(inFile, dvdPtr -> title);
getline(inFile, dvdPtr -> leadActor);
getline(inFile, dvdPtr -> supportingActor);
getline(inFile, dvdPtr -> genre);
cin >> dvdPtr -> year;
cin >> dvdPtr -> rating;
getline(inFile, dvdPtr -> synopsis);
dvdPtr -> next = head;
head = dvdPtr;
dvdPtr = new DVDNode;
}
delete dvdPtr;
inFile.close();
return head;
}
我还有一个如下所示的输出函数:
void OutputList(DVDNode* head, string outputFile)
{
ofstream outFile;
outFile.open(outputFile.c_str());
DVDNode* dvdPtr;
dvdPtr = head;
while(outFile && dvdPtr != NULL)
{
outFile << dvdPtr -> title;
outFile << dvdPtr -> leadActor;
outFile << dvdPtr -> supportingActor;
outFile << dvdPtr -> genre;
outFile << dvdPtr -> year;
outFile << dvdPtr -> rating;
outFile << dvdPtr -> synopsis;
dvdPtr = dvdPtr -> next;
}
outFile.close();
}
这是主要代码的样子:
// Variables
string inputFile;
string outputFile;
DVDNode* head;
// Input
cout << "Enter the name of the input file: ";
getline(cin, inputFile);
head = CreateList(inputFile);
// Output
cout << "Enter the name of the output file: ";
getline(cin, outputFile);
OutputList(head, outputFile);
我很抱歉,如果这是一个愚蠢的问题,我在网上找不到任何关于链表的好教程,我真的不明白为什么在我输入输入文件名后这没有做任何事情。
提前感谢您的帮助。
编辑:
所以我解决了cin问题,但现在有一个不同的问题。当我的输入文件如下所示:
Yankee Doodle Dandee
James Cagney
Joan Leslie
Musical
Biography
1942
8
This film depicts the life of the renowned musical composer, playwright, actor, dancer and singer George M. Cohan.
X-Men
Hugh Jackman
Patrick Stewart
Action
Action
2000
7
All over the planet, unusual children are born with an added twist to their genetic code.
列表继续,这种格式有大约10部电影。但是,在运行程序后,输出文件如下所示:
Title: Yankee Doodle Dandee
Lead Actor: James Cagney
Supporting Actor: Joan Leslie
Genre: Musical
Year: 1735357008
Rating: 544039282
Synopsis:
如果我将inFile.ignore(100, '\n');
添加到我在CreateList
中读取的行下面的genre
函数,则输出如下所示:
Title: This film depicts the life of the renowned musical composer, playwright, actor, dancer and singer George M. Cohan.
Lead Actor:
Supporting Actor: X-Men
Genre: Hugh Jackman
Year: 0
Rating: 0
Synopsis:
Title: Yankee Doodle Dandee
Lead Actor: James Cagney
Supporting Actor: Joan Leslie
Genre: Musical
Year: 1942
Rating: 8
Synopsis:
编辑:对不起,我弄清楚了。这只是一些忽视的问题。感谢。
答案 0 :(得分:6)
它没有挂起,它正在等待您的输入,因为您有:
cin >> dvdPtr -> year; // read year from std input!!
cin >> dvdPtr -> rating;
在函数CreateList
中。此函数打开用户指定的文件并从中读取DVD字段。
将以上行更改为:
inFile >> dvdPtr -> year; // read year from file.
inFile >> dvdPtr -> rating;