简体   繁体   English

使用字符串作为变量名(C ++)

[英]Using String as Variable Name (C++)

Assume I have Variable called "Volume", for example. 例如,假设我有一个名为“ Volume”的变量。 I now have a file with Settings in it. 我现在有一个带有设置的文件。 Every Settings looks like this: ": I now go through this file from top to bottom, and I want the program to store the Setting in a Variable with an equal Name. 每个设置看起来都像这样:“:现在,我从上到下浏览此文件,并且我希望程序将设置存储在具有相同名称的变量中。

eG if there is "Volume: 76", I want the program to write "76" into the Variable "Volume". 例如,如果存在“ Volume:76”,我希望程序将“ 76”写入变量“ Volume”。 How can I make the program to get the right Variable just by the string? 如何使程序仅通过字符串获得正确的变量? Is this even possible? 这有可能吗?

There is no code yet, since I haven't started working on it yet. 目前还没有代码,因为我还没有开始处理它。 I was making thoughts about it. 我正在考虑。

You can't use variables directly, since the name must be existent at compile time, but reading a file is runtime. 您不能直接使用变量,因为名称必须在编译时存在,但是读取文件是在运行时。

You can use std::map though. 您可以使用std :: map。 Each settings will be a key, and the value will be read in. 每个设置都将是一个键,并且将读取该值。

std::map<std::string, std::string> settings;
settings["volume"] = "76";

But, the values ("76" in this case) will be strings as well. 但是,(在这种情况下“76”)中的值将是字符串为好。 You can not use differing types directly. 您不能直接使用其他类型。 I think, its possible with type erasure, but thats really advanced (and iam not fluent with it!). 我认为,通过类型擦除实现它是可能的,但是那确实很先进(而且我不太熟练!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM