使用输入字符串作为变量名 [英] Use input string as variable name

查看:69
本文介绍了使用输入字符串作为变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入的是例如"banana",我想打印出香蕉的千卡.我尝试过类似的操作(但失败了):

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;

我知道我可以使用if语句来做到这一点

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

string input;
cin >> input;

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

但是当我有1000多种食物时,我必须编写很多代码...

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;

我的班级,Food.h代码:

My class, the Food.h code:

#pragma once

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

food.cpp代码:

The food.cpp code:

CFood::CFood()
{
    Kcal = 0;
}
CFood::~CFood()
{
}

推荐答案

将所有食物存储在 std :: map 或相关容器中,并通过其 string 进行访问.code>键:

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;

请记住,以上内容是伪的,您通常需要采取一些保护措施来保护您的项目免于崩溃(例如,检查 Foods.find(stuff)!= Foods.end()等)

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

这篇关于使用输入字符串作为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆