tiggares
tiggares

Reputation: 505

double to string in c++

I'm trying to convert the expression "5 + b * 18" to "5+16.89*18". My problem is inside the while loop. I managed to remove the spaces.

My code:

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);
 }

Can anyone help me?

Ty

Upvotes: 1

Views: 384

Answers (3)

kevlar1818
kevlar1818

Reputation: 3125

Use sprintf. It's great for converting most primitive types into strings.

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

Upvotes: 0

Attila
Attila

Reputation: 28782

insert() will shift the contents of the string to the right after the inserted text, but does not delete the character at the given position. You should use replace(), specifying a size of ` (to replace just a single character)

Upvotes: 1

Michael Wild
Michael Wild

Reputation: 26381

Is this homework? If not, I'd really advice against doing this kind of parsing yourself. There are dedicated libraries for this kind of things which have been extensively tested, such as muParser.

Upvotes: 1

Related Questions