fork(10) download
  1. #include <limits> // std::numeric_limits
  2. #include <algorithm> // std::reverse
  3.  
  4. namespace cppx {
  5. using std::numeric_limits;
  6. using std::reverse;
  7.  
  8. typedef numeric_limits<long> Long_info;
  9. int const long_digits = Long_info::max_digits10;
  10. int const long_bufsize = long_digits + 2;
  11.  
  12. inline void unsigned_to_decimal( unsigned long number, char* buffer )
  13. {
  14. if( number == 0 )
  15. {
  16. *buffer++ = '0';
  17. }
  18. else
  19. {
  20. char* p_first = buffer;
  21. while( number != 0 )
  22. {
  23. *buffer++ = '0' + number % 10;
  24. number /= 10;
  25. }
  26. reverse( p_first, buffer );
  27. }
  28. *buffer = '\0';
  29. }
  30.  
  31. inline auto decimal_from_unsigned( unsigned long number, char* buffer )
  32. -> char const*
  33. {
  34. unsigned_to_decimal( number, buffer );
  35. return buffer;
  36. }
  37.  
  38. inline void to_decimal( long number, char* buffer )
  39. {
  40. if( number < 0 )
  41. {
  42. buffer[0] = '-';
  43. unsigned_to_decimal( -number, buffer + 1 );
  44. }
  45. else
  46. {
  47. unsigned_to_decimal( number, buffer );
  48. }
  49. }
  50.  
  51. inline auto decimal_from( long number, char* buffer )
  52. -> char const*
  53. {
  54. to_decimal( number, buffer );
  55. return buffer;
  56. }
  57. } // namespace cppx
  58.  
  59. #include <iostream>
  60. using namespace std;
  61.  
  62. auto main() -> int
  63. {
  64. using cppx::decimal_from;
  65. using cppx::long_bufsize;
  66. using cppx::Long_info;
  67.  
  68. char spec[long_bufsize];
  69.  
  70. cout << decimal_from( Long_info::min(), spec ) << endl;
  71. cout << decimal_from( Long_info::min() + 1, spec ) << endl;
  72. cout << decimal_from( 0, spec ) << endl;
  73. cout << decimal_from( Long_info::max() - 1, spec ) << endl;
  74. cout << decimal_from( Long_info::max(), spec ) << endl;
  75. }
  76.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
-2147483648
-2147483647
0
2147483646
2147483647