Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Integer to string conversion?
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
AsianSensation




PostPosted: 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
Sponsor
sponsor
wtd




PostPosted: 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




PostPosted: 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




PostPosted: 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




PostPosted: 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




PostPosted: Thu Mar 31, 2005 8:42 pm   Post subject: (No subject)

and also, that is not more efficient in anyway
bugzpodder




PostPosted: Thu Mar 31, 2005 9:04 pm   Post subject: (No subject)

also

atoi(myString.c_str())

does it in one line Razz
Andy




PostPosted: Thu Mar 31, 2005 9:07 pm   Post subject: (No subject)

integer to string jack, not string to integer
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Thu Mar 31, 2005 9:09 pm   Post subject: (No 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.
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 9 Posts ]
Jump to:   


Style:  
Search: