C++: Use input string as variable name

こ雲淡風輕ζ 提交于 2020-01-04 13:03:20

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/23117238/c-use-input-string-as-variable-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!