Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string from a file in a function

Tags:

c++

casting

I have this function in c++

double f_x(double y , string sfy )
{
  return sfy;
}
  1. I want to read the string sfy from a file and pass it to the f_x function.
  2. sfy contains something like y or cos(y) or exp(y).
  3. when I pass y and sfy to the f_x, I want f_x calculates sfy and return it.

I can do number 1 and 3 but the problem is that the type of f_x is double and sfy is string, so I get error.

I can not change the type of f_x to anything else it should be double or float.

How can I overcome this problem namely what should I do in order to f_x returns sfy as double.

like image 201
MOON Avatar asked Sep 11 '26 22:09

MOON


1 Answers

Something like this, perhaps:

#include <map>
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>

std::map<std::string, double(*)(double)> m;

double f_x(double y , std::string sfy )
{
    if (m.find(sfy) == m.end()) throw "Invalid operation.";
    return m[sfy](y);
}

int main()
{
    m["exp"] = std::exp;
    m["cos"] = std::cos;
    m["sin"] = std::sin;

    std::ifstream file("test.txt");
    std::string op;
    std::getline(file, op);

    std::cout << f_x(42.0, op);
}
like image 97
jrok Avatar answered Sep 14 '26 12:09

jrok