I'm having some troubles in my exercise with C++ language: The exercise consists of: Have a bus with 55 sits for travelers, I have to be able to add, edit, and remove travelers from this bus.
So far my code works but I don't know why when I add or show the variable are not stored in my array properly.
#include <iostream>
using namespace std;
//Clase que representa un objeto de un viejero
class Viajero {
public:
string nombre;
};
//declaración de las funciones
void anadirViajero();
void mostraViajeros();
//declaración de las variables globales
static Viajero autobus[55];
int main() {
anadirViajero();
mostraViajeros();
return 0;
}
void anadirViajero(){
string nombre;
bool check = false;
for(Viajero viajero : autobus){
if(viajero.nombre == "" && check == false){
cout<<"Nombre Viajero: ";
cin>>nombre;
viajero.nombre = nombre;
check = true;
}
}
}
void mostraViajeros(){
int count = 0;
for(Viajero viajero : autobus){
count++;
cout<<"Nombre: ";
cout<<viajero.nombre;
}
cout<<"Total de Viajeros: "<<count;
}
I'm not sure if my global variable is a correct approach to solve this exercise. I tried to put static in the declaration but still not storing the values.
this here:
if(viajero.nombre == "" && check == false){
cout<<"Nombre Viajero: ";
cin>>nombre;
viajero.nombre = nombre;
check = true;
}
is incorrect , as soon as you add 1 user, you set the flag check to true
, and this is blocking the condition to ad a new viajero
if a viajero has a state like checked or not then that should be defined in the class
like:
class Viajero {
public:
string nombre;
bool check;
};
As well as the fact that you'll only ever read in one name (as pointed out by ΦXocę 웃 Пepeúpa ツ), you also have another problem: your line viajero.nombre = nombre;
sets the name for a Vialero
object that it entirely local to the for loop and never assign anything to the members of your array.
To fix this, make the 'iterator' variable a reference to the array, as follows (note the &
symbol after the Viajero
):
for (Viajero& viajero : autobus) { // viajero MUST be a REFERENCE if you want to change the array element(s)
if (viajero.nombre == "" && check == false) {
cout << "Nombre Viajero: ";
cin >> nombre;
viajero.nombre = nombre;
// check = true; // If you leave this line in, only the first name will get read!
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.