简体   繁体   English

使用函数中文件的字符串

[英]Using string from a file in a function

I have this function in c++ 我在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. 我想从文件中读取字符串sfy并将其传递给f_x函数。
  2. sfy contains something like y or cos(y) or exp(y). sfy包含y或cos(y)或exp(y)之类的东西。
  3. when I pass y and sfy to the f_x, I want f_x calculates sfy and return it. 当我将y和sfy传递给f_x时,我希望f_x计算sfy并返回它。

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. 我可以做第1和第3,但问题是f_x的类型是double,sfy是字符串,所以我得到错误。

I can not change the type of f_x to anything else it should be double or float. 我无法将f_x的类型更改为其他任何应该为double或float的内容。

How can I overcome this problem namely what should I do in order to f_x returns sfy as double. 我怎样才能克服这个问题,即我应该怎么做才能使f_x返回sfy为double。

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

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

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