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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

How to convert int to string

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

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.



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