Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
May 27, 1997

How to convert int to string

Question:
I am looking for a generic way to convert an int to a string. It cannot be platform- or compiler-specific in its implementation.

Answer:
The standard C++ library defines the classes std::istringstream and std::ostringstream that can be used for manipulations on strings to accommodate various datatypes. The way to convert an integer to a string would be, for example:

std::string convertToString(int i)
{
	ostringstream o;
	o << i;
	return o.str (); // returns std::string
}
Many compilers do not implement this version of the stream classes yet; if your compiler vendor does not, you can use the older version, called strstream, in the exact same way.

If all else fails you can always use the standard C library call sprintf to do the conversion. Here's how:

void foo ()
{
	char buf [10];
	sprintf (buf,"%d",10); 
	puts(buf); // will print 10..
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date