[英]Using string from a file in a function
I have this function in c++ 我在c ++中有这个功能
double f_x(double y , string sfy )
{
return 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.