I do not know about the "better", but this version uses std::locale
, etc.
#include <iostream> #include <locale> #include <sstream> template<class Char> class MyFacet : public std::numpunct<Char> { public: std::string do_grouping() const { return "\3"; } Char do_thousands_sep() const { return ' '; } }; std::string number_fmt(unsigned long n) { std::ostringstream oss; oss.imbue(std::locale(oss.getloc(), new MyFacet<char>)); oss << n; return oss.str(); } int main() { std::cout << number_fmt(123456789) << "\n"; }
EDIT . Of course, if your ultimate goal is to print the values to
ostream
, you can skip storing them in
string
as a whole.
#include <iostream> #include <locale> #include <sstream> #include <cwchar> template <class Char> class MyFacet : public std::numpunct<Char> { public: std::string do_grouping() const { return "\3"; } Char do_thousands_sep() const { return ' '; } }; int main(int ac, char **av) { using std::locale; using std::cout; // Show how it works to start with cout << 123456789 << "\n"; // Switch it to spacey mode locale oldLoc = cout.imbue(locale(cout.getloc(), new MyFacet<char>)); // How does it work now? cout << 456789123 << "\n"; // You probably want to clean up after yourself cout.imbue(oldLoc); // Does it still work? cout << 789123456 << "\n"; }
Robᵩ Aug 31 2018-11-11T00: 00Z
source share