C++ : Trim a string to a single char, 然后将该字符转换为 float

标签 c++ c++11

我正在编写一个程序,从文件中获取多项式表达式,然后使用提供的变量求解多项式。示例:

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/

相关文章:

c++ - 当g++静态链接pthread时,导致段错误,为什么?

c++ - 当构造函数抛出 vector.emplace 或 vector.emplace_back 时会发生什么?

c++ - 了解 VirtualAlloc 中的基地址

c++ - 模板模板和部分特化 : a puzzle

multithreading - 这种释放/获取语义的使用是否包含潜在的数据竞争?

C++ std::function 找不到正确的重载

c++ - 具有相似索引的值的总和

c++ - 使用 boost spirit (longest_d) 解析 int 或 double

c++ - 现代 C++ 中的唯一指针

c++ - 由于 header 中的特化初始化而避免重复符号?