Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting an integer in C++

Tags:

c++

string

g++

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

XXX-XX-XXX

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

What's a good way to do this?

like image 330
neuromancer Avatar asked May 12 '10 02:05

neuromancer


1 Answers

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, "-");
};
like image 112
goldPseudo Avatar answered Nov 15 '22 20:11

goldPseudo