itoa implement for std string


/ Published in: C++
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.