We had a fun bit of comparison with several ways to do this, in the forum. Unfortunately, it gets pushed back far enough and it all disappears from our view.
You can do this by working with bits, working with arithmetic, or working dynamically with a string.
I'll describe the dynamic way. You have a function:
Code:
void printWithCommas(int num) { //your parameter would be a long
int i, j, len;
char ch;
char c[SIZE+10]; //where SIZE is a #define SIZE 10,20,whatever.
/* c will handle up to 9 commas in a number */
i=0;
j=1; //j simplifies some logic in the while loop
while(num > 0) {
c[i]= num % 10 + '0';
/*
The +'0', makes the int digit, print out as a char with %c.
Without it, you'll see weird char's: faces, cards, etc.
Num % 10 gets the value of the rightmost digit of num
because we use a base 10 numbering system. You knew
there would be *some* arithmetic in here. ;)
*/
num /= 10; //remove the rightmost digit from the number
++i;
if(j%3==0 && num>0) {
c[i++]=',';
}
++j;
}
/* Add the end of string char ('\0', to c at c[i].
Now you have the answer but it's in reverse order.
So either reverse it (or print it char by char in reverse order),
and print it, and you're done.
*/
}
I'm posting this because it's difficult to describe this way of doing it, and make it understandable, to those who have not been exposed to it. At least, not if you attended public schools.
The arithmetic way of doing this is straightforward, but boring.