[英]Extracting the right values from strings
int a = 10;
int b = 5;
char test[]= "bread";
a = a + test[0];
cout << a << endl;
Basically i want to use the value of the integer b.基本上我想使用 integer b 的值。 In this example the first char of the string is a 'b' so i want to use the value of b and not the ascii value.
在这个例子中,字符串的第一个字符是'b',所以我想使用 b 的值而不是 ascii 值。
I tried casting it like this but did not work.我尝试像这样铸造它,但没有奏效。
a = a + (int)test[0];
The cout should be 15; cout 应该是 15;
Variable names don't exist at runtime.变量名在运行时不存在。 You could use a
std::map
(or std::unordered_map
) to associate names with values.您可以使用
std::map
(或std::unordered_map
)将名称与值相关联。 Simple example:简单的例子:
std::map<char, int> variables;
variables['a'] = 10;
variables['b'] = 5;
std::string test = "bread"; // In C++ prefer std::string over char[]
variables['a'] = variables['a'] + variables[test[0]];
cout << variables['a'] << endl; // Prints 15
The feature you want can only be properly supported in a very dynamic language, like python or tcl.您想要的功能只能在非常动态的语言中得到适当的支持,例如 python 或 tcl。 C++ is a compile time language, it has no idea about what your variable b's name means, to the compiler it's just some random symbol.
C++ 是一种编译时语言,它不知道变量 b 的名称是什么意思,对编译器来说它只是一些随机符号。 You might change b to abcde, and compiler won't care less.
您可以将 b 更改为 abcde,编译器不会在意。
Once you gave up on the variable name, there is still something that can do.一旦你放弃了变量名,仍然可以做一些事情。
std::map<char, int> some_map;
some_map['b'] = 5;
char test[]= "bread";
int a = 10;
a += some_map[test[0]];
cout << "a = " << a << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.