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

问题描述

如果输入是例如香蕉,我想打印香蕉的kcal。我尝试这样的(失败):

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

有我的声明和我的香蕉对象的定义。每个对象都有kcal。

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 或相关容器中, c $ c> string key:

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

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

05-21 03:54