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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date