Computer Science Canada

Integer to string conversion?

Author:  AsianSensation [ Thu Feb 24, 2005 7:17 pm ]
Post subject:  Integer to string conversion?

What is an easy way to convert from a integer to a string object (not an array of characters)?

Author:  wtd [ Thu Feb 24, 2005 7:43 pm ]
Post subject: 

Use a stringstream.

code:
#include <sstream>
#include <string>

int main()
{
   int foo = 42;
   std::string bar;
   std::stringstream baz;

   baz << foo;
   baz >> bar;

   return 0;
}

Author:  AsianSensation [ Thu Feb 24, 2005 7:51 pm ]
Post subject: 

Wow, cool, I read your other tutorial on conversion using stringstream, I thought it was just extracting numbers from strings only, didn't know it could work the other way too. Way cool. Thanks alot.

Author:  cimnik029 [ Wed Mar 30, 2005 8:19 pm ]
Post subject: 

or you could do it like this, if you want to deal with std::strings.

#include <sstream>
#include <string>

int main()
{
int foo = 42;
std::string bar;
std::stringstream baz;

baz << foo;
bar = baz.str();

return 0;
}

Its more efficient if, say, its going straight to the console you can avoid a temporary variable.

The stringstream class functions like any other stream class like ifstream or ofstream

Author:  Andy [ Thu Mar 31, 2005 8:41 pm ]
Post subject: 

wtf are you talking about? how does that save an temp variable? if ur going to say something, at least type it in english so ppl dont have to read it 5 times to understand you, and make sure you know what your talking about first

Author:  Andy [ Thu Mar 31, 2005 8:42 pm ]
Post subject: 

and also, that is not more efficient in anyway

Author:  bugzpodder [ Thu Mar 31, 2005 9:04 pm ]
Post subject: 

also

atoi(myString.c_str())

does it in one line Razz

Author:  Andy [ Thu Mar 31, 2005 9:07 pm ]
Post subject: 

integer to string jack, not string to integer

Author:  wtd [ Thu Mar 31, 2005 9:09 pm ]
Post subject: 

bugzpodder wrote:
also

atoi(myString.c_str())

does it in one line Razz


Don't mix C and C++, please.

Stringstreams are the optimal way to do this.


: