Posted By

vikiyou on 03/30/11


Tagged

itoa c++


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

nbegiter


itoa implement for std string


 / Published in: C++
 

URL: http://www.strudel.org.uk/itoa/

A implement of itoa with c++, std string. itoa is function that convert a integer to a string.

  1. /**
  2.   * C++ version 0.4 std::string style "itoa":
  3.   * Contributions from Stuart Lowe, Ray-Yuan Sheu,
  4.  
  5.   * Rodrigo de Salvo Braz, Luc Gallant, John Maloney and Brian Hunt
  6. */
  7.  
  8. #include <string>
  9.  
  10. std::string itoa_cpp(int value, int base)
  11. {
  12. std::string buf;
  13.  
  14. // check that the base if valid
  15. if (base < 2 || base > 16)
  16. return buf;
  17.  
  18. enum { kMaxDigits = 35 };
  19. buf.reserve( kMaxDigits ); // Pre-allocate enough space.
  20.  
  21. int quotient = value;
  22.  
  23. // Translating number to string with base:
  24. do {
  25. buf += "0123456789abcdef"[ std::abs( quotient % base ) ];
  26. quotient /= base;
  27. } while ( quotient );
  28.  
  29. // Append the negative sign
  30. if ( value < 0 )
  31. buf += '-';
  32.  
  33. std::reverse( buf.begin(), buf.end() );
  34. return buf;
  35. }

Report this snippet  

You need to login to post a comment.