C++ 双精度转换为c+中的字符串+;

C++ 双精度转换为c+中的字符串+;,c++,string,double,C++,String,Double,我试图将表达式“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); w

我试图将表达式“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);
 }
double number=16.89;
未找到尺寸;
ostringstream转换;
字符串str(“5+b*18”);
str.erase(删除(str.begin()、str.end()、“”)、str.end());
found=str.find_first_of(有效字符);
while(找到!=string::npos)
{        
转换使用。它非常适合将大多数基本类型转换为字符串

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

这是家庭作业吗?如果不是的话,我真的建议你不要自己做这种解析。有专门的库用于这类事情,已经过广泛的测试,例如。

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

我没有投反对票,但我怀疑这是因为
sprintf
要求您自己进行内存管理,这很容易出错。对于这类问题,我建议使用
boost::lexical\u cast
(假设海报希望使用部分boost库)。唯一容易发生的错误是人为错误。如果“容易出错”更优雅、更快速,我会选择“容易出错”。我也同意Boost实现。不用说,我不认为我的回答是“没有用”无论如何。你是对的,我也不认为这有理由投反对票。我只是想提供一个可能的解释。我不知道如何使用boost::lexical_cast@tiggares很简单:
std::string numberString=boost::lexical_cast(数字)
,其中
number
是上面的
double
变量。这将创建一个包含
16.89
的字符串。您现在必须将此字符串插入变量
str
的正确位置。