Converting a numerical value to a string and vice-versa

amrith92 amrith92 is offline Offline May 21st, 2009, 5:21 pm |
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:
  1. 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:
  1. 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....
Quick reply to this message  
C++ Syntax
  1. /*
  2.   This Function (Fn I) converts a variable of
  3.   data-type DataType into a string
  4. */
  5. template <typename DataType>
  6. string convertToString(DataType MyValue)
  7. {
  8. // Creates a Output String Stream to hold
  9. // the variable passed (MyValue)
  10. ostringstream OutStream;
  11.  
  12. // Enter the variable into the stream
  13. OutStream << MyValue;
  14.  
  15. // Return the stream as an array of
  16. // characters(string)
  17. return (OutStream.str());
  18. }
  19.  
  20. /*
  21.   This Function (Fn II) converts a string into
  22.   a variable of data-type DataType
  23. */
  24. template <typename DataType>
  25. DataType convertFromString(string MyString)
  26. {
  27. // Stores the return value
  28. DataType retValue;
  29.  
  30. // Creates an Input String Stream to extract
  31. // the contents of the string
  32. istringstream InStream(MyString);
  33.  
  34. // Read contents of String and store in retValue
  35. InStream >> retValue;
  36.  
  37. // Return the value in the desired DataType
  38. return retValue;
  39. }
0
William Hemsworth William Hemsworth is offline Offline | May 21st, 2009
Good simple snippet
 
0
amrith92 amrith92 is offline Offline | May 22nd, 2009
Thanks
 
0
tux4life tux4life is offline Offline | May 24th, 2009
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!
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC