# Small problem with converting

## Recommended Posts

I am trying to convert an int to a string for a small game I am making to learn SDL. As this question is asked three or four times aday, I looked through a few old posts and decided to go like:
//int Life;
//std::string Health;
//std::stringstream ss;

ss << Life;
Health = ss.str();
But, as this portion of code is repeated, 'Life' gets added to 'ss' instead of just placed there. So, I can fix this in two different ways: clearing 'ss', or doing something like:
ss = Life;
Health = ss.str();
How can I do either? I know nothing of stringstream.

##### Share on other sites
the 'str' member function is overloaded as a mutator as well as an accessor, so you can write 'ss.str("")'.

Alternately, use a different stream, or do the work in a function (so that a different stream is implicitly used for each function call).

Alternately, if you are trying to create one big string for output with all the bits of information in it - then just do that. Let the stringstream be your buffer for the whole output message, and append the numbers and also intervening text.

##### Share on other sites
There are different ways to do it, but I'll show you one. It's pretty cool.
[source#include <iostream>#include <stdlib.h>using namespace std;int main(){    int num = 100;    char buffer[10];        itoa(num, buffer, 10);        cout << buffer << endl;        num = 85;        itoa(num, buffer, 10);        cout << buffer << endl;}
What it does is converts the number and places it in buffer. This way you dont even have to deal with strings (although you could always append it do the string).

 Dang!! beat by Zahlman. His is probably better, although itoa is something rather nifty in times. [/Edit]

##### Share on other sites
Thanks.

@Mike: I'm going with Zahlman's way, but I'll definately look into the itoa thing, I'be seen it mentioned before.

##### Share on other sites
Quote:
 Original post by MikeTacularThere are different ways to do it, but I'll show you one. It's pretty cool.
Perhaps, if by 'pretty cool' you mean non-standard and unsafe :-) See here for more info.
Quote:
 This way you dont even have to deal with strings.
You should want to deal with std strings - in almost all cases they'll make your life easier, not harder.
Quote:
 ...but I'll definately look into the itoa thing, I'be seen it mentioned before.
I wouldn't bother - you're almost certainly better off using the C++ standard library.

##### Share on other sites
Quote:

Quoted for relevence. This is the same question, with several answers (some good, some bad).

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627731
• Total Posts
2978831

• 10
• 9
• 21
• 14
• 12