从命令行获取运算符,并将其用作代码中的运算符
Taking an operator from command line and using them as an operator inside the code
我将从一个例子开始
me@blabla ./example + 3 5
应返回 8。
我接受参数,但我如何将"+"从
char* opp = argv[1];
到 a
+
在我的代码中使用?
因为我想使用相当多的运算符,有没有办法在不使用大的 if 语句的情况下做到这一点?
我希望这很清楚,谢谢!
您必须
从char
到运算符进行某种映射。假设您已经在一些整数变量 x
和 y
中3
和5
,简单的解决方案是使用 switch
语句:
switch (opp[0]) {
case '+': result = x + y; break;
case '-': result = x - y; break;
// and so on...
}
或者,您可以有一个从 char
秒到 std::function<int(const int&,const int&)>
std::map
:
typedef std::function<int(const int&,const int&)> ArithmeticOperator;
std::map<char, ArithmeticOperator> ops =
{{'+', std::plus<int>()},
{'-', std::minus<int>()},
// and so on...
};
int result = ops[opp[0]](x,y);
像这样的东西怎么样:
char op = argv[1][0];
if (op == '+')
add(argv[2], argv[3]);
或者可能:
switch (op)
{
case '+':
add(argv[2], argv[3]);
break;
...
}
您可以根据要接受的运算符列表测试给定运算符。
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main(int argc, char* argv[])
{
if (argc <= 3)
{
std::cout << "<op> <num1> <num2>n";
return 1;
}
const std::string op = argv[1];
const int arg1 = boost::lexical_cast<int>(argv[2]);
const int arg2 = boost::lexical_cast<int>(argv[3]);
cout << arg1 << op << arg2 << " = ";
if (op == string("+")) // <== Here is where you turn "+" into +
{
cout << arg1 + arg2 << "n";
}
else if (op == string("*")) // <== or "*" into *
{
cout << arg1 * arg2 << "n";
}
else
{
cout << "I don't know how to do that yet.n";
return 2;
}
return 0;
}
此问题最通用的解决方案是构建解析树,以便可以将其扩展到更大的输入。
解析树基本上是二叉树,它提供了操作数和运算符之间关系的表示,叶子之前的每个节点都是一个运算符,叶子本身就是操作数,因此当您想要分析或解释表达式时,您可以从树的底部开始,并在树向上时解析表达式。
最简单的方法是制作递归下降解析器,创建两个堆栈,一个用于运算符,一个用于操作数,当您找到运算符时,将它们与它们各自的操作数一起推送到堆栈上,当您到达优先级较低的运算符时,您根据需要从堆栈和操作数中弹出一个运算符并创建一个节点。
如果您不想经历创建自己的解析器的麻烦,我发现 boost 有一些实用程序可以为您做到这一点。 但我没有亲自使用过它们,所以你必须查看文档以查看它们是否有任何用处。 http://www.boost.org/doc/libs/1_34_1/libs/spirit/doc/trees.html
相关文章:
- 为什么模数运算符不适用于该代码
- 逻辑运算符上出现错误代码 a')'
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- std::string == 运算符在代码中不起作用
- 将 c++ 代码转换为 python,使用运算符?
- 为什么无法覆盖涉及第三方代码的模板类的运算符<<?
- 重载 <= 运算符,但程序以退出代码 -1073741571 (0xC00000FD) 结尾
- 如何翻译这个给定代码中的 ::* 运算符和member_fn?
- 代码块编译错误与运算符<<不匹配
- 为多个签名使用相同的代码重载赋值运算符?
- 赋值运算符在我制作类模板时使代码崩溃
- 在使用具有相等运算符定义的抽象类时,如何定义父类以减少代码重复?
- 删除运算符如何在我的代码中工作
- 在混合 c 和 c++ 代码中使用运算符 new
- 任何机构都可以在运算符重载中解释这行代码
- 没有运算符"[]"匹配这些操作数/没有模板化代码
- 试图重写代码以包括模量运算符
- 重载新运算符 - 此代码不应产生错误
- Visual studio:E0349 没有运算符<<匹配这些操作数(但代码中没有字符串)
- C++类型转换运算符代码,在 Visual Studio 2012 中无法编译,但在 Visual Studio 2005 中工作正常