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()
{
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With