我正在编写一个程序,从文件中获取多项式表达式,然后使用提供的变量求解多项式。示例:
f(5.0) = 7x^2 – 9
所以基本上我通过以下方式逐行提取文件:
string line;
getline(inputfile,line);
现在,我需要获取 f 内部的变量(在本例中为 5)并将其设置为等于我命名为变量的 float 。我知道 atof(我正在使用 minGW 4.9.2 [我的编程类(class)需要])所以我不能使用 stof。我目前尝试提取这个 float 看起来像这样:
float variable;
for(int i = 0; i<line.length(); i++) {
if(isdigit(line[i]) {
variable = atof(line[i]) // THE ERROR IS HERE
break; // so we only get the first digit
}
}
我在这里迷路了,不知道该怎么做。我只需要将 5.0(或任何可能的值)设置为等于我的变量 float。感谢您的帮助。
最佳答案
它可能会按照您的意图执行任务。
string str = "f(5.0) = 7x^2 – 9";
string startDEL = "(";
string stopDEL = ")";
unsigned first = str.find(startDEL);
unsigned last = str.find(stopDEL);
string strNew = str.substr (first+1,last-first-1);
std::cout << << atof(strNew.c_str()) << std::endl;
关于C++ : Trim a string to a single char, 然后将该字符转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624131/