I think there's something wrong with the cycle

I tried to add three drivers to each bus using a cycle. However, I doubt this cycle is correct, because it works only for the first few buses. Here's the link https://onlinegdb.com/nsHpcEyj6
First this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  while(!fbus.eof()){
  	cin_string(carnumber,fbus);
  	cin_string(carcolor,fbus);
    cin_string(carbrand,fbus);
    cin_int(caryear,fbus);
    cin_float(carpetrol,fbus);
    cin_int(carseat,fbus);
    cin_string(carroute,fbus);
    Bus bus;
    bus.set_number(carnumber);
	bus.set_color(carcolor);
	bus.set_brand(carbrand);
	bus.set_year_of_production(caryear);
	bus.set_petrol(carpetrol);
	bus.set_passengersseats(carseat);
	bus.set_route(carroute);
	buses.push_back(bus);
  }

The eof() is not for this use. You have to test the state of the input stream after the input operation if you want to know whether the input operation did succeed.

Two more obvious solutions:
1
2
3
4
5
6
// Read, test, and use custom Bus constructor:
while ( fbus >> carnumber >> carcolor >> carbrand
         >> caryear >> carpetrol >> carseat >> carroute ) {
  buses.emplace_back( carnumber, carcolor, carbrand,
         caryear, carpetrol, carseat, carroute );
}

1
2
3
4
5
// with istream& operator>>( std::istream&, Bus& )
Bus bus;
while ( fbus >> bus ) {
  buses.emplace_back( bus );
}

Same with the Drivers.


Now, how do you know that 'drivers' has 3 elements?
1
2
3
4
5
for ( int i=0; i<buses.size(); i++ ) {
  for ( int j=0; j<3; j++ ) {
    buses[i].add_driver( &drivers[j] );
  }
}

You don't. You have to check that:
1
2
3
4
5
for ( Bus& bus : buses ) {
  for ( int j=0; j<3 && j<drivers.size(); j++ ) {
    bus.add_driver( &drivers[j] );
  }
}

There is an another issue: If you do something to vector 'drivers' after this, that can invalidate the pointers.
Topic archived. No new replies allowed.