how do I use a string in a struct to decide which data to show?

1

good. My question is to know how to use the string shows to decide which part of body to show. ex: if you enter "name" show me your name.

#include<iostream>
using namespace std;

struct vector2d{
    double x,y;
};

struct cuerpo{
    string nombre;
    double masa;
    vector2d pocicion,aceleracion,velocidad;
};

int main(){       //nombre, masa, pocicion,aceleracion,velocidad
    cuerpo test = {"andres",25.25,{2.3,5.2},{1.2,5.4},{5.4,9.5}};
    string muestra;

    cout<<"que desea mostrar? : ";
    cin>>muestra;//masa
    cout<<test.cuerpo.muestra;//deberia de aparecer masa (25.25) Y SI,
                              //ya se que esa es una manera INCORRECTA de hacerlo,
                              //pero no se cual es la manera correcta.
}
    
asked by bassily 03.08.2016 в 01:57
source

1 answer

1

One way would be to leave the selection of what should be shown in charge of the body class; for example, with a member function that returns a string to show with cout.

string cuerpo::mostrar(const string& muestra)
{
    if(muestra == "nombre")
        return nombre;
    else if(muestra == "masa")
        return to_string(masa);
    // else if(etcétera...)
    return "";
}
    
answered by 05.08.2016 / 20:28
source