Advertisement
zhangsongcui

Integer to string

May 18th, 2011
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. template<typename T>
  2. std::basic_string<T> itos(int _Val, const unsigned _Radix=10)
  3. {
  4.     int lg;
  5.     if (_Radix<2 && _Radix>36)
  6.         throw std::invalid_argument("The radix is out of bound.");
  7.     if (_Val>0)
  8.         lg=0;
  9.     else if (_Val<0)
  10.         lg=1, _Val=-_Val;
  11.     else
  12.         return std::basic_string<T>()+=T('0');//What the...
  13.     for (int temp=_Val; temp; temp/=_Radix)
  14.         ++lg;
  15.     //std::use_facet<std::ctype<T> >(std::locale()).widen
  16.     std::basic_string<T> Result(lg, T('0'));
  17.     typename std::basic_string<T>::reverse_iterator iter=Result.rbegin();
  18.     for (; _Val; ++iter, _Val/=_Radix)
  19.     {
  20.         int temp=_Val%_Radix;
  21.         if (temp<10)
  22.             *iter=temp+T('0');
  23.         else
  24.             *iter=temp+(T('A')-10);
  25.     }
  26.    
  27.     if (iter!=Result.rend())
  28.         *iter=T('-');
  29.     return Result;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement