从命令行获取运算符,并将其用作代码中的运算符

Taking an operator from command line and using them as an operator inside the code

本文关键字:运算符 代码 命令行 获取      更新时间:2023-10-16

我将从一个例子开始

me@blabla ./example + 3 5

应返回 8。

我接受参数,但我如何将"+"从

char* opp = argv[1];  

到 a

+ 

在我的代码中使用?

因为我想使用相当多的运算符,有没有办法在不使用大的 if 语句的情况下做到这一点?

我希望这很清楚,谢谢!

您必须

char到运算符进行某种映射。假设您已经在一些整数变量 xy35,简单的解决方案是使用 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