简体   繁体   中英

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

I have been asked a question in an interview and want to know program approach to solve it.

Que: We have a text file which contain operation need to be performed in a program. User can update this text file and change the operation ie text file can contain + for addition or - for subtraction. Program has two variable ie a and b, reads text file, perform operation and display result. If text file contain +, then program should return sum of a and b and if text file has - then program should return ab. User can put any operation in text file.

I have given two approaches:

  1. Program can have switch statement in it. If text file has +, program check switch statement and perform a+b operation as per switch statement, like wise for for other operations. This answer was rejected as we have to hard code all possible operations in switch.

  2. I can use oracle and run query for any operation ie if text file has +, then I can create a sql string like 'select a+b into :result from dual;' and run an embedded sql in program. Database will execute sql and return output for any valid operation and program need not to hard code all possible operation. I have given this answer as I was giving interview for C++/C and pro*c. But panel was not satisfied with this approach also.

So what is the best approach to solve this problem through a program ?

Probably something like this, a lookup table for functions with similar prototype

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;
}

And then use it based on your text file

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

Where - , 8 , 4 are from your text file

For reading the expression from the input file, you can use the standard reading method that Standard Library offers:

#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;
}

(code taken from cplusplus.com )

About translating that string you get from the file... you get very deep into expression trees. For working with the expression trees, you can take a look at the code below. This is something I wrote in the past to explain somebody about this concept:

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; 
};

you can then use it like so...

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

You can read more about this concept on Wikipedia .

I hope this helps you!

In my opinion They just want to read the character +,-,* and put this character in between the variables and execute the statement.

for how to convert the string into expression see this answer Convert string to mathematical evaluation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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