I've always had a hard time with arrays of objects when it comes to storing user input for each objects members and then outputting them. I created a class called VideoGame and an array of objects called Games[5]. What I'm trying to do here is get user input for each data member in an object, store that user input in its corresponding data member, and then in the end, output the result of the object in question such as Games[0]. I know how to create a normal array using user input for each element, and then outputting a given element from the array, but the problem I'm having here is I'm not sure how to do that same thing for array of objects.
class VideoGame
{
public :
// constructors
void setTitle( const string& title ) { this->title = title; }
string getTitle() { return title; }
// other members
private :
string title;
// other members
};
int main ()
{
VideoGame games[ 5 ];
string foo;
for( size_t i = 0; i < 5; i++ ) {
cin >> foo;
games[ i ].setTitle( foo ); // set title
cout << games[ i ].getTitle(); // print title
// ...
}
}
Once you fix your code problems, an array of objects is just the same as any other array. You reference objects by the correct index and treat that single object as you would treat a single instance of the object.
1 2 3 4 5 6 7 8 9 10 11 12
class car
{
int cost;
};
car mycars[5]; //Declare an array of 5 objects.
int i;
for(i = 0; i < 5; ++i)
{
std::cin >> mycards[i].cost; //Set the cost of each car in the array.
}
Thanks you guys for your help. I modified my program and got it to build without any error, but it's not entirely executing the way that it should. Everything seems to be working normally, except for when it gets to the part about asking for input on the games dev. It just kind of skips over that part and jumps right to the end of the program. I can't see anything that looks wrong with that part of the program.
Not to be off topic, but does anyone know of any good C++ books. I've been practicing with C++ now for about a month and am looking for something that I can read that is tailored more towards C++ beginners. I was looking at possibly getting: