1,105,334 Community Members

Converting a numerical value to a string and vice-versa

Member Avatar
(amrith92)
Reputation Points: 119 [?]
Q&As Helped to Solve: 24 [?]
Skill Endorsements: 3 [?]
 
0
 

These functions, to some, may seem trivial, but many people have queried in the forums on this topic numerous times.

The functions are templated, so that it can accommodate any data-type that the user wishes to use (For example, the same function can be used for converting variables of type long , int , double etc into strings, and vice-versa).

The first function, Fn I ( convertToString ), is capable of converting a variable of any data-type into a string.
Sample Function Call:

string MyInt = convertToString<int>(10);

The second function, Fn II ( convertFromString ), can convert a string into a variable of any data-type.
Sample Function Call:

int MyNumber = convertFromString<int>("45");

*Note*: You will have to include the header files - <sstream> and <string.h> for the code to work...

Hope this snippet helps....

/*
     This Function (Fn I) converts a variable of
     data-type DataType into a string
*/
template <typename DataType>
string convertToString(DataType MyValue)
{
     // Creates a Output String Stream to hold
     // the variable passed (MyValue)
     ostringstream OutStream;
    
     // Enter the variable into the stream
     OutStream << MyValue;
    
     // Return the stream as an array of
     // characters(string)
     return (OutStream.str());
}

/*
     This Function (Fn II) converts a string into
     a variable of data-type DataType
*/
template <typename DataType>
DataType convertFromString(string MyString)
{
     // Stores the return value
     DataType retValue;
    
     // Creates an Input String Stream to extract
     // the contents of the string
     istringstream InStream(MyString);
    
     // Read contents of String and store in retValue
     InStream >> retValue;
    
     // Return the value in the desired DataType
     return retValue;
}
Member Avatar
William Hemsworth
Posting Virtuoso
1,546 posts since Mar 2008
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 158 [?]
Skill Endorsements: 10 [?]
 
0
 

Good simple snippet :)

Member Avatar
amrith92
Junior Poster
188 posts since Jul 2008
Reputation Points: 119 [?]
Q&As Helped to Solve: 24 [?]
Skill Endorsements: 3 [?]
 
0
 

Thanks :)

Member Avatar
mvmalderen
Nearly a Posting Maven
2,370 posts since Feb 2009
Reputation Points: 2,071 [?]
Q&As Helped to Solve: 282 [?]
Skill Endorsements: 40 [?]
 
0
 

And it's well commented and it addresses a common beginner's problem :)
Though I'm not so sure about the <string.h> you've to include, it has to be <string>, string.h contains several functions which operate on c-strings ...

Nice snippet!

You
Post:
Start New Discussion
Tags Related to this Article