在 C++ 中双精度为字符串

double to string in c++

本文关键字:字符串 双精度 C++      更新时间:2023-10-16

我正在尝试将表达式"5 + b * 18"转换为"5 + 16.89 * 18"。我的问题在 while 循环内。我设法删除了空格。

我的代码:

double number = 16.89;
size_t found;
ostringstream converted;
string str ("5 + b * 18");
str.erase(remove(str.begin(),str.end(),' '),str.end());
found = str.find_first_of (VALID_CHARS);
while (found != string::npos)
 {        
  converted << fixed << setprecision (8) << number;        
  str.insert(found, converted.str());                                               
  found = str.find_first_of (VALID_CHARS,found + 1);
 }

谁能帮我?

> insert()会将字符串的内容移到插入文本之后的右侧,但不会删除给定位置的字符。 您应该使用 replace() ,指定大小 ' (仅替换单个字符)

这是家庭作业吗?如果没有,我真的建议不要自己做这种解析。对于这种经过广泛测试的东西,有专门的库,比如muParser。

使用 sprintf。它非常适合将大多数基元类型转换为字符串。

int main()
{
  double number = 16.89;
  char buffer [50];
  sprintf(buffer, "5 + %f * 18",number);
}