链接列表从文本文件



我对指针和链表很陌生,但我正试图编写一个简单的程序,从文本文件读取数据到链表。输入函数有问题。它看起来像这样:

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: 

如果我在genre中读取的行正下方的CreateList函数中添加一个inFile.ignore(100, 'n');,那么输出看起来像这样:

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: 
编辑:对不起,我明白了。这只是再忽略几个人的问题。谢谢。

它没有挂起,它正在等待您的输入,因为您有:

cin >> dvdPtr -> year;   // read year from std input!!
cin >> dvdPtr -> rating;
函数CreateList中的

。这个函数打开用户指定的文件并从中读取DVD字段。

将以上行改为:

inFile >> dvdPtr -> year;   // read year from file.
inFile >> dvdPtr -> rating;

相关内容

  • 没有找到相关文章

最新更新