Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Jun 16, 2000



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

Converting a Number to a String

The standard strstream family of classes enables you to convert numeric values into their string representation easily. You need to instantiate an strstream object, insert the numeric value to it using the overloaded << operator, and then extract the string from the strstream object using the str() member function. The following program converts a float variable to a string object using strstream:

#include <strstream>
#include <string>
using namespace std;
int main()
 ostrstream s;
 float f = 6.6777;
 s<<f; //insert f into the stream
 string st = s.str(); //copy into a string

Note that strstream overload to << operator for all built-in types, e.g., int, float, double, char, pointers, etc. In the following example, a strstream object stores the value of a void pointer and then prints it on the screen:

int main()
 ostrstream s;
 void *p = &s // take address of s
 s<<p; // insert address into the stream
 cout<< s.str(); // display the address
Danny Kalev
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