Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
What's a good way to insert commas into numeric output in c++? For instance long l = 12300 would be output as 12,300.

As far as I know, there is no standart way to do so. However you may try to implement a function that will do it for you.
I wonder,though, what will be its contribution compared to the effort you will
make to write it...

I have an assignment to write three output manipulators that take parameters. One of them is supposed to do the comma thing. The book I have for this class says parameterized manipulators are beyond it's scope, so now my greater problem is finding a reference for doing those.

I'm not sure if there is a ready to use function that would do the job for you, and if you get marks for this part of the program they don't want you to use such a function (if there is one).
So just try to write a simple function that uses divisions by 1000 to cut your number and add commas into it.

If you need more information about Manipulators just look in "C++ programming laguage, 3rd edition" by B.Stroustrup, pages 631 to 636.
Note: in other editions, the pages may differ.

I don't know c++ programming but I know it supports Regular Expressions. So, doing a substitution on a var might solve the comma insertion problem.
Here's 2 options using Perl syntax:
$x = 1234567890;
option 1,
$x =~ s/(?=\d)(?=(\d\d\d)+$)/,/g;option 2
while ($x =~ s/(\d)((\d\d\d)+\b)/$1,$2/g) {};In either case, $x is now 1,234,567,890
I borrowed these regexs from O’Reilly’s Mastering Regular Expressions by Jeffrey Friedl.
However, they only work with integers. If you need to work with real numbers, we’ll need to make some changes.

Best bet is to write a function which will insert a comma after every third integer space. Shouldnt be to hard. just some math.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |