1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
// Some binary functions
double set( double a = 1, double b = 1 ) { return b; }
double add( double a, double b ) { return a + b; }
double sub( double a, double b ) { return a - b; }
double mul( double a, double b ) { return a * b; }
double div( double a, double b ) { return a / b; }
// Map function name to function;
map<string,double(*)(double,double)> fmap = { { "set", set },
{ "add", add },
{ "sub", sub },
{ "mul", mul },
{ "div", div } };
int main()
{
double result = 0.0;
// ifstream in( "input.txt" );
istringstream in( "set 0"
"add 2"
"sub 3"
"mul 5"
"div 2" );
string op;
double arg;
while ( in >> op >> arg )
{
if ( fmap.count( op ) ) // If this operation is found
{
result = fmap[op]( result, arg );
cout << op << " " << arg << " ---> " << result << '\n';
}
else
{
cout << "Operation " << op << " not understood\n";
}
}
}
|