Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use input string as variable name

Tags:

c++

class

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()
{
}
like image 385
editsons Avatar asked Jan 24 '26 02:01

editsons


1 Answers

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.)

like image 191
MrDuk Avatar answered Jan 25 '26 17:01

MrDuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!