If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

How to manipulate vector of class type in C++

Hi all,
I built a class type 'books' which includes the title and the price of a particular book. And I want to use vectors to store all the books information I have. This code should be able to get all the books' information and store them into the vector.

But it seems no possible to use xxx.push_back(yyy) or iterators to add new elements to vector<books>.... Could anyone show me the correct way to deal with this kind of problem?

Re: How to manipulate vector of class type in C++

Thank you Drmmr.
But I still didn't get how to use push_back when you are dealing with a vector of class type.
For example, in my code, the class type has two private members 'price' and 'title'. Obviously we cannot
access them and modify them without calling the the member function.

Re: How to manipulate vector of class type in C++

Thank you Eri523! That helps a lot!
But I met another problem with my code using getline(cin,temp);
I changed my code to this. The thing is, the first time in the do...while loop, everything is good.
But after i input 'y' to execute another do...while loop, it just skip the new_book.getname() part.
I believe it's something wrong with the getline usage. Because if i changed it to cin>>temp, it works just
fine.

Re: How to manipulate vector of class type in C++

Originally Posted by ertss

But I met another problem with my code using getline(cin,temp);
I changed my code to this. The thing is, the first time in the do...while loop, everything is good.
But after i input 'y' to execute another do...while loop, it just skip the new_book.getname() part.
I believe it's something wrong with the getline usage. Because if i changed it to cin>>temp, it works just
fine.

The problem is that after you read the price using >> the endline following the price remains in the input stream. Next time you call getline, it will read an emtpy line (i.e. only the endline character). The easiest way to avoid this is to use getline all the time, then use a stringstream to parse the input.

Re: How to manipulate vector of class type in C++

Originally Posted by D_Drmmr

The problem is that after you read the price using >> the endline following the price remains in the input stream. Next time you call getline, it will read an emtpy line (i.e. only the endline character). The easiest way to avoid this is to use getline all the time, then use a stringstream to parse the input.