从字符串中提取正确的值

Extracting the right values from strings

本文关键字:提取 字符串      更新时间:2024-09-22
int a = 10;
int b = 5;
char test[]= "bread";
a = a + test[0];
cout << a << endl;

基本上,我想使用整数b的值。在这个例子中,字符串的第一个字符是"b",所以我想使用b的值,而不是ascii值。

我试着把它选成这样,但没有成功。

a = a + (int)test[0];

cout应该是15;

运行时不存在变量名。可以使用std::map(或std::unordered_map(将名称与值相关联。简单示例:

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

您想要的功能只能在非常动态的语言中得到适当的支持,比如python或tcl。C++是一种编译时语言,它不知道变量b的名字意味着什么,对编译器来说,它只是一些随机符号。您可能会将b更改为abcde,编译器也不会在意。

一旦你放弃了变量名称,仍然有一些事情可以做。

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;