0

Possible Duplicate:
Alternative to itoa() for converting integer to string C++?

I want to convert an int variable to string to put it in the textbox.

I have tried this code:

int x = 123;
std::ostringstream osstream;
osstream << x;
std::string string_x = osstream.str();

But it doesn't work.

Community
  • 1
  • 1
  • In what way is it useless? Have you checked the contents of `string_x` in a debugger? – Anders Abel Nov 12 '11 at 21:43
  • 1
    What doesn't work? I know that this works for me. – netcoder Nov 12 '11 at 21:47
  • 1
    what exactly is wrong with the above code? That is how you would turn an integer into a string. – tpar44 Nov 12 '11 at 21:49
  • 1
    What exactly do you mean with "it doesn't work"? Does it not compile, and if so, what is the compiler error message? Does it segfault? Does it give some other string content than expected, and if so, what is it? I can't see why this code shouldn't work. – celtschk Nov 12 '11 at 21:55

1 Answers1

-3

Try using stringstream instead

std::stringstream osstream;
osstream << x;
std::string string_x = osstream.str();
std::cout << string_x << std::endl;

Works on my computer.

I had another issue once where I had to append a whitespace to that, so try this too:

std::stringstream osstream;
osstream << x << " "; 
alcoholtech
  • 180
  • 1
  • 5
  • 1
    stringstream makes absolutely no difference in this usage. Also, it strikes me as horrible convention to name the variable osstream... – sehe Nov 12 '11 at 22:01