neuromancer neuromancer - 4 months ago 27
C++ Question

Formatting an integer in C++

I have an 8 digit integer which I would like to print formatted like this:


I would like to use a function that takes an int and returns a string.

What's a good way to do this?


This is how I'd do it, personally. Might not be the fastest way of solving the problem, and definitely not as reusable as egrunin's function, but it strikes me as both clean and easy to understand. I'll throw it in the ring as an alternative to the mathier and loopier solutions.

#include <sstream>
#include <string>
#include <iomanip>

std::string format(long num) {
  std::ostringstream oss;
  oss << std::setfill('0') << std::setw(8) << num;
  return oss.str().insert(3, "-").insert(6, "-");