1

我的功能有问题,它应该打印出存储的书籍列表

void PrintBooklist(vector<BookList>&book)
{
    for(int i=0; i<book.size(); i++)
    {   
        if (book[i].memNumBor = -1)
            cout<<book[i].title<<endl;
    }
}

但它会打印出“标题”这个词;几次,但将其留空。我检查最后的大小以确保添加的任何内容都被推回,但我无法读出它。提前致谢!

int main()
{   
    vector<BookList>book;
    vector<MemInfo>member;
    string memberfile;
    string bookfile;
    ofstream fout;
    ifstream fin;

    cout << "\n\t\t\tWelcome to Library Management Services!"<<endl<<endl;

    Read_Member(member, fin, memberfile);
    Read_Book(book, fin, bookfile);

    SignIn(member, book, fin, fout, memberfile, bookfile); 
    return 0;
}

void Read_Member(vector<MemInfo> &member, ifstream &Fin, string &memberfile) 
{
    MemInfo temp;
    cout<<"Please enter the name of the file that contains the member information: ";
    getline(cin,memberfile);

    Fin.open(memberfile.c_str());

    if(Fin.fail())
    {
        cout<<endl<<"File containing the member information does not exist.\n"<<endl;
        exit (0);
    }

    ReadInfoMem(Fin);
    while (!Fin.eof())
    {   
        member.push_back(temp);
        ReadInfoMem(Fin);
    }
    Fin.close();

    for (int i=0; i<member.size(); i++)
    {
        cout<<endl<<member[i].lName<<endl;
    }
}
4

1 回答 1

2

你行分配 memNumBor

if (book[i].memNumBor = -1)

你想要的是平等检查

if (book[i].memNumBor == -1) // note the double '=='

更新:

编辑添加更多代码后,我注意到以下内容:

MemInfo temp;

// ...snip...

ReadInfoMem(Fin);            // presumably this reads the member info from 'Fin'?
while (!Fin.eof())
{   
    member.push_back(temp);  // and you add an *empty* 'temp' object to 'member'
    ReadInfoMem(Fin);
}

我预计正在发生的事情是您正在从Finin读取ReadInfoMem到局部MemInfo变量,但是您没有将填充的内容返回MemInfo到将其添加到member向量中的封闭函数。

我建议使用return-by-valuepass-by-reference

按值返回

MemInfo ReadInfoMem(ifstream& fs)
{
    MemInfo temp;
    // populate temp
    return temp;
}

// in your calling code:
temp = ReadInfoMem(Fin);

引用传递

void ReadInfoMem(ifstream& fs, MemInfo& temp)
{
    // populate temp
}

// in your calling code:
ReadInfoMem(Fin, temp);
于 2012-12-03T02:12:15.463 回答