我正在开发一个保存车辆库存的程序,所以我为它创建了一个结构。它还需要保留驱动程序列表,因此我为此创建了一个嵌套结构。这是代码:
struct Vehicle{
string License;
string Place;
int Capacity;
struct Driver{
string Name;
int Code;
int Id;
}dude;
};
我要求用户输入,然后使用此函数将结构放在向量中:
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);
};
现在,我需要的是在矢量中打印结构。我做了以下功能:
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;
}
}
}
但它只打印出第一个结构的元素,打印出驱动程序信息所在的随机数。你能告诉我哪里是我的错吗?除嵌套结构外,其他所有内容都打印正常。
答案 0 :(得分:1)
Vehicle::Driver dude;
您在这里声明了另一个变量,它与dude
(newV
)中的Vehicle
无关。
将代码更改为:
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);
};