从字符串中提取正确的值
Extracting the right values from strings
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;
相关文章:
- 清除输入缓冲区后未提取字符串流
- 提取字符串中的随机单词
- 提取C++字符串
- 如何提取字符串中的特定值
- 如何提取字符串中的整数?
- 正则表达式:从模式字符串 1.string2'string3 中提取字符串,其中字符串 1 可以包含 '." 字符
- C - 从逗号分隔的浮点线提取字符串
- 如何使用正则表达式提取字符串的不匹配部分
- 处理从 std::istream 中提取字符串的空字符串大小写
- 可视化从文本C++中提取字符串数据
- 如何在C++中有效地提取字符串模式
- 分析文本文件以提取字符串
- C++:从两个符号之间提取字符串
- 提取字符串的一部分并将部分放入字符数组和另一个字符串变量C++
- 如何在c++中提取字符串的一部分
- 使用getline(),然后从用户输入中提取字符串(使用c++)
- 尝试从文本文件中读取列表,然后搜索文本文件,并在c++中提取字符串
- 试图从c++文本文件的单行中提取字符串的一部分
- 从字符数组中提取字符串
- 从JavaScript代码中提取字符串