Monday, 25 July 2016

C++ String Integer Conversion


There are several methods but I prefer this way.

1
2
3
4
5
6
7
template <typename T>
  string NumberToString ( T Number )
  {
     ostringstream ss;
     ss << Number;
     return ss.str();
  }
Usage: NumberToString ( Number ); 

1
2
3
4
5
6
7
template <typename T>
  T StringToNumber ( const string &Text )
  {
     istringstream ss(Text);
     T result;
     return ss >> result ? result : 0;
  }
Usage: StringToNumber<Type> ( String ); 

But #include <sstream> must be added at the top.


ref:
http://www.cplusplus.com/articles/D9j2Nwbp/

No comments:

Post a Comment