lizagub
lizagub

Reputation: 21

Trouble getting the info stored in the structures in the vector

I am having an issue with my function, it is supposed to print out the list of books stored

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

but it prints out the word "Title;" a few times but leaves it blank. I check the size at the end to make sure whatever is added is being pushed back and it is, but I cannot read it out. Thanks in advance!

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;
    }
}

Upvotes: 1

Views: 58

Answers (1)

Steve Lorimer
Steve Lorimer

Reputation: 28659

You line assigns memNumBor

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

What you want is equality check

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

Update:

After the edit to add more code, I noticed the following:

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);
}

I expect what is happening is that you're reading from Fin in ReadInfoMem into a local MemInfo variable, but you're not returning the populated MemInfo to your enclosing function which adds it to your member vector.

I would suggest either a return-by-value, or a pass-by-reference.

return-by-value

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

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

pass-by-reference

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

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

Upvotes: 2

Related Questions