Hello everyone,

I'm writing a code and in there and I need to convert a char which contains any of "+", "-", "*", "/" into a real operator.
As an example let's say I have:

char myOp = '+';
int op1 = 10, op2 = 20;

cout << op1 myOp op2 << endl;

How could I do that.

Of course I know I could use "switch", but I am looking for a more professional way of doing it.("If there exist one!!!").

Thanks a lot.

Recommended Answers

All 3 Replies

Someone asked something similar before in another forum and you could do something like this.

class thing {
private:
  typedef int (*_fptr)(int,int); // Typedef this for readibility of functino pointer
  std::map<std::string, _fptr> mfp; // Associate a string to a function pointer

public:
  void add( std::string id, _fptr f ) {
    mfp[id] = f; // Add a function pointer (shuld check if the function already exists)
  }

  int call(std::string func, int l, int r){
    return mfp[func]( l, r ); // Call the function (should check if function already exists)
  }

};

int add( int l, int r ) {
  return l+r;
}
int sub( int l, int r ) {
  return l-r;
}
// Simple functions

int main( void ) {
  thing t;
  t.add("add",add);
  t.add("sub",sub);// Add the functions to the class

  int l(5), r(3);
  std::string func;
  std::cout<< "Enter function (add,sub): "; // Ask for the function that's to be called
  std::cin >> func;
  std::cout<< t.call(func,l,r) << "\n"; // Call it
  
  return 0;
}

Maybe it's too much, maybe not... but I think it does what you want.

Token pasting operator.

#include <iostream>

using namespace std;
#define paster( n,m,k ) cout << "\n" << (token##n  k token##m)
int main()
{
  int token9 =30;
  int token8=10;
  paster(9,8,-);
  paster(9,8,+);
  paster(9,8,*);
  return 0;
}
commented: nice! +1

Thank you very much twomers cause your solution is kind of what I had in mind but it's really long way for doing it.

Adatapost, that was one interesting solution. So I am gonna give it a go.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.