1
我很新的指针和链表,但我试图编写一个简单的程序,从文本文件读入数据到链接列表。我在输入功能时遇到问题。它看起来像这样:从文本文件链接列表
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');
向右,我在genre
阅读线下CreateList
功能,比输出看起来是这样的:
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:
编辑:对不起,我想通了。这只是一个更多的忽略问题。谢谢。在功能CreateList
cin >> dvdPtr -> year; // read year from std input!!
cin >> dvdPtr -> rating;
:
你是什么意思什么都不做?你的意思是它挂了吗? – forsvarir 2011-04-12 09:20:28
是的,对不起。它只是挂起。我尝试在输入函数的while循环中放置测试cout,但它们没有输出。 – Michael 2011-04-12 09:22:09
你知道你正在从while循环中读取cin吗? – forsvarir 2011-04-12 09:23:19