fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <iomanip>
  5. #include <cstdint>
  6. #include <vector>
  7.  
  8. std::string format_commas(uint64_t value)
  9. {
  10. std::stringstream ss;
  11. std::vector<uint16_t> parts;
  12. do {
  13. parts.push_back(short(value % 1000));
  14. value /= 1000;
  15. } while (value > 0);
  16. for (std::vector<uint16_t>::reverse_iterator i = parts.rbegin(); i != parts.rend(); ++i) {
  17. if (i != parts.rbegin())
  18. ss << std::setw(3) << std::setfill('0');
  19. ss << *i;
  20. if (i + 1 != parts.rend())
  21. ss << ',';
  22. }
  23. return ss.str();
  24. }
  25.  
  26. std::string format_commas_2(uint64_t value)
  27. {
  28. std::string result;
  29. std::stringstream ss;
  30. std::vector<int> parts;
  31. do {
  32. parts.push_back(value % 1000);
  33. value /= 1000;
  34. } while (value > 0);
  35. for (std::vector<int>::reverse_iterator i = parts.rbegin(); i != parts.rend(); ++i) {
  36. if (i != parts.rbegin())
  37. ss << std::setw(3) << std::setfill('0');
  38. ss << *i;
  39. if (i + 1 != parts.rend())
  40. ss << ',';
  41. }
  42. result = ss.str();
  43. return result;
  44. }
  45.  
  46. int main()
  47. {
  48. std::cout << '(' << format_commas(0) << ')' << std::endl;
  49. std::cout << '(' << format_commas(8) << ')' << std::endl;
  50. std::cout << '(' << format_commas(18) << ')' << std::endl;
  51. std::cout << '(' << format_commas(128) << ')' << std::endl;
  52. std::cout << '(' << format_commas(1238) << ')' << std::endl;
  53. std::cout << '(' << format_commas(12348) << ')' << std::endl;
  54. std::cout << '(' << format_commas(123458) << ')' << std::endl;
  55. std::cout << '(' << format_commas(1234568) << ')' << std::endl;
  56. }
  57.  
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
(0)
(8)
(18)
(128)
(1,238)
(12,348)
(123,458)
(1,234,568)