2

If the input is for example "banana", I want to print the kcal of banana. I tried something like this (and failed):

string input;
cin >> input;
cout << input.Kcal << endl;

I know that I can do it with if-statements like:

string input;
cin >> input;

if(input == "banana")
{
    cout << banana.Kcal << endl;
}

But there I must write very much code when I have more then 1000 foods...

There is my declaration and definition of my banana object. Every object has kcal.

food banana;
banana.Kcal = 89;

My class, the Food.h code:

#pragma once

class CFood
{
public:
    CFood();
    ~CFood();
    float Kcal;
}

The food.cpp code:

CFood::CFood()
{
    Kcal = 0;
}
CFood::~CFood()
{
}
1
  • 1
    std::unordered_map<std::string, CFood> would seem a reasonable fit for your needs. Commented Apr 16, 2014 at 18:26

2 Answers 2

7

Store all of your foods in a std::map or related container, and access them by their string key:

std::map<string, Food> Foods;
Foods.insert(std::make_pair("banana", Banana));

// later..

cin >> stuff;
cout << Foods.at(stuff).kcal << endl;

Keep in mind that the above is pseudo, and you'd typically want to make some safeguards to protect your project from crashing (e.g., checking for Foods.find(stuff) != Foods.end(), etc.)

Sign up to request clarification or add additional context in comments.

Comments

3

Unfortunately C++ is a compiled language which means that it loses information about names in code in a compilation process (translation to machine code). This means you can't use any information from your code at runtime (class names, variable names and so on) without manually storing it somewhere. You're out of luck here if you want to do it this way - you'll need to use dynamic / interpreted language such as PHP or JavaScript.

If you want to do this in C++ you need to create a hash map with name->value entries and then display its value based on program input (MrDuk provided excellent example in his answer).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.