繁体   English   中英

需要从文本文件中读取操作并在程序中执行

[英]Need to read an operation from text file and perform it in a program

在面试中有人问我一个问题,想知道解决该问题的程序方法。

队列:我们有一个文本文件,其中包含需要在程序中执行的操作。 用户可以更新此文本文件并更改操作,即文本文件可以包含+(用于加法)或-(用于减法)。 程序具有两个变量,即a和b,读取文本文件,执行操作并显示结果。 如果文本文件包含+,则程序应返回a和b的和,如果文本文件包含-,则程序应返回ab。 用户可以在文本文件中进行任何操作。

我给出了两种方法:

  1. 程序中可以包含switch语句。 如果文本文件带有+,则对switch语句进行编程,并按照switch语句执行a + b操作,对于其他操作也一样。 由于我们必须对switch中所有可能的操作进行硬编码,因此该答案被拒绝。

  2. 我可以使用oracle并对任何操作运行查询,即如果文本文件具有+,则可以创建一个sql字符串,例如“将a + b选择为:result from dual;”。 并在程序中运行嵌入式sql。 数据库将执行sql并返回任何有效操作的输出,而程序无需对所有可能的操作进行硬编码。 我在接受C ++ / C和pro * c采访时给出了这个答案。 但是小组也对这种方法不满意。

那么,通过程序解决此问题的最佳方法是什么?

大概是这样的,一个具有类似原型的函数的查找表

int add(int a,int b)
{
    return a+b;
}

int sub(int a,int b)
{
    return a-b;
}

typedef int (*function_cb)(int,int);
std::map<string, function_cb> callBacks;

.....
void init_lookup()
{
    callBacks["+"] = &add;
    callBacks["-"] = &sub;
}

然后根据您的文本文件使用它

 int res = callBacks["-"](8,4);

- 84是从文本文件

要从输入文件中读取表达式,可以使用标准库提供的标准读取方法:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

(代码取自cplusplus.com

关于翻译从文件中获取的字符串,您将深入了解表达式树。 为了使用表达式树,您可以看一下下面的代码。 这是我过去写过的一些东西,用来解释这个概念:

class Token
{
public:
  enum TokenTypes { operator_token, operand_token };

  Token();
  Token( std::string token );
  ~Token(); // we are not inheriting, so no need to be virtual
  Token(const Token &in);
  Token& operator=(const Token &in);
  TokenTypes getId() const;

  // you need to set the left/right from addToken(), see class Tree
  void setLeft(Token* left);
  void setRight(Token* right);   
  const Token* getLeft();
  const Token* getRight();

private:

  // when creating the Token you need to be able to identify
  // what TokenType the string is
  TokenTypes tokenId( std::string token );

  TokenTypes m_id; // type of token
  std::string m_token; // the actual string token e.g. "+", "12", ..
  Token* m_left; // the pointers to the children left or right in a binary tree
  Token* m_right; 

};

class Tree
{
public:
  Tree();
  ~Tree(); // clean up 
  void addToken( std::string token ); // this adds a token to the tree
private:
  Token* m_root; 
};

然后可以像这样使用它...

std::string strToken
Tree T; 
while ( getNextStringToken(strToken) )
{
  Token* newToken = new Token(strToken);
  T.addToken(newToken);
}

您可以在Wikipedia上阅读有关此概念的更多信息。

我希望这可以帮助你!

在我看来,他们只想读取+,-,*字符并将其放在变量之间并执行语句。

对于如何将字符串转换为表达看到这个答案将字符串转换为数学评价

我认为这个问题更多地是在运算符重载方面,您可以定义当操作数是函数/不是标准变量时普通运算符将执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM