Reputation: 157
I am working on a program that keeps inventory of vehicles, so I created a struct for it. It also needs to keep a list of the drivers, so I created a nested struct for that. Here's the code:
struct Vehicle{
string License;
string Place;
int Capacity;
struct Driver{
string Name;
int Code;
int Id;
}dude;
};
I ask for user input and then put the structs in a vector using this function:
void AddVehicle(vector<Vehicle> &vtnewV){
Vehicle newV;
Vehicle::Driver dude;
cout << "Enter license plate number: " << endl;
cin >> newV.License;
cout << "Enter the vehicle's ubication: " << endl;
cin >> newV.Place;
cout << "Enter the vehicle's capacity: " << endl;
cin >> newV.Capacity;
cout << "Enter the driver's name: " << endl;
cin >> dude.Name;
cout << "Enter the driver's code: " << endl;
cin >> dude.Code;
cout << "Enter the driver's identification number: " << endl;
cin >> dude.Id;
vtnewV.push_back(newV);
};
Now, what I need is to print the structs inside the vector. I made the following function:
void PrintVehicle(vector<Vehicle> vtnewV){
{
vector<Vehicle> ::iterator i;
for (i = vtnewV.begin(); i != vtnewV.end(); i++)
{
cout << "License plate: " << i->License << endl;
cout << "Ubication: " << i->Place << endl;
cout << "Capacity: " << i->Capacity << endl;
cout << "Driver's name: " << i->dude.Name << endl;
cout << "Driver's code: " << i->dude.Code << endl;
cout << "Id: " << i->dude.Id << endl;
cout << " " << endl;
}
}
}
But it only prints out the elements of the first struct, printing out random numbers where the driver's info should be. Can you tell me where's my mistake? Everything else prints fine, except for the nested struct.
Upvotes: 2
Views: 265
Reputation: 172934
Vehicle::Driver dude;
You're declaring another variable here, which has nothing to do with the dude
inside the newV
(Vehicle
).
Change the code to:
void AddVehicle(vector<Vehicle> &vtnewV){
Vehicle newV;
//Vehicle::Driver dude; // delete it here
cout << "Enter license plate number: " << endl;
cin >> newV.License;
cout << "Enter the vehicle's ubication: " << endl;
cin >> newV.Place;
cout << "Enter the vehicle's capacity: " << endl;
cin >> newV.Capacity;
cout << "Enter the driver's name: " << endl;
cin >> newV.dude.Name;
cout << "Enter the driver's code: " << endl;
cin >> newV.dude.Code;
cout << "Enter the driver's identification number: " << endl;
cin >> newV.dude.Id;
vtnewV.push_back(newV);
};
Upvotes: 1