If you want to get rid of the large switch
/if
statement, you can use map
with string
and a pointer-to-member. Assuming your stock
struct, you can use:
Define the map (for doubles here) and initialize it:
std::map<std::string,double stock::*> double_members;
double_members["price"]=&stock::price;
double_members["volume"]=&stock::volume;
double_members["eps"]=&stock::eps;
And use it to look up some values:
stock stock1;
std::string input;
std::cin >> input;
if (double_members.find(input)!=double_members.end())
std::cerr << "Value for " << input << " is: " << stock1.*double_members[input] << std::endl;
else
std::cerr << "There's no field called " << input << std::endl;
It's limited to a single type, but you can't have a statement like std::cerr << A;
and have A
's type resolved during runtime. If you care only about string
(or any other, but always the same) representation of the values, then you can wrap map
s for different types in a class that searches all of them and outputs the value converted to a string
(or something).
But it's probably easier to have the if
statement, unless the struct
is really big.