Author |
Message |
AsianSensation
|
Posted: 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)? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
wtd
|
Posted: Thu Feb 24, 2005 7:43 pm Post subject: (No 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;
} |
|
|
|
|
|
|
AsianSensation
|
Posted: Thu Feb 24, 2005 7:51 pm Post subject: (No 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. |
|
|
|
|
|
cimnik029
|
Posted: Wed Mar 30, 2005 8:19 pm Post subject: (No 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 |
|
|
|
|
|
Andy
|
Posted: Thu Mar 31, 2005 8:41 pm Post subject: (No 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 |
|
|
|
|
|
Andy
|
Posted: Thu Mar 31, 2005 8:42 pm Post subject: (No subject) |
|
|
and also, that is not more efficient in anyway |
|
|
|
|
|
bugzpodder
|
Posted: Thu Mar 31, 2005 9:04 pm Post subject: (No subject) |
|
|
also
atoi(myString.c_str())
does it in one line |
|
|
|
|
|
Andy
|
Posted: Thu Mar 31, 2005 9:07 pm Post subject: (No subject) |
|
|
integer to string jack, not string to integer |
|
|
|
|
|
Sponsor Sponsor
|
|
|
wtd
|
Posted: Thu Mar 31, 2005 9:09 pm Post subject: (No subject) |
|
|
bugzpodder wrote: also
atoi(myString.c_str())
does it in one line
Don't mix C and C++, please.
Stringstreams are the optimal way to do this. |
|
|
|
|
|
|