Tuesday, 6 September 2016

C++ Update Object attributes using set function




I'm writing a bookshop program. The program stores a number of books with their associated values (title, price, isbn, author) in a vector. One of the functions I'm trying to write is to search the vector by isbn and update the values of whichever book matches. Here is my code




void UpdateOnIsbn(vector  booklist)
{
string searchisbn;
char response;
string booktitle;
string author;
double price;
string ISBN;

cout << "Please enter an ISBN to be searched: ";

cin >> searchisbn;

for (int i = 0; i < booklist.size(); i++)
{
if (booklist[i].HasISBN(searchisbn))
{
booklist[i].Display();

cout << "Would you like to update the details of this book? (Y/N): ";
cin >> response;


if (response != 'n' && response != 'N')
{


cout << endl << "Please Enter New Title for book: ";
cin >> booktitle;
booklist[i].SetTitle(booktitle);

cout << endl << "Please Enter New Author ";

cin >> author;
booklist[i].SetAuthor(author);

cout << endl << "Please Enter New Price ";
cin >> price;
booklist[i].SetPrice(price);

cout << endl << "Please Enter New ISBN ";
cin >> ISBN;
booklist[i].SetISBN(ISBN);






}

}
}
}



The function seems to work as it looks for new values to be entered but after it runs the old values are not replaced when I display the books again. Please help



Here is an example of one of the set functions:



void CBooks::SetPrice(double NewPrice)
{
m_Price = NewPrice;
}


Answer



You need to pass booklist by reference:



void UpdateOnIsbn(vector & booklist)


Otherwise the vector is copied and only this copy is modified.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...