425,526 Members | 2,207 Online Need help? Post your question and get tips & solutions from a community of 425,526 IT Pros & Developers. It's quick & easy.

# comma formatted integer output (LONG POST)

 P: n/a /*Thanks again to thos who helped with my 'more hand written integer pow() functions (LONG POST)' query. I needed to write a function to write out integers and after looking at some stuff on the web I felt they look a bit code-heavy so... A) If you think the code attached is reasonable, consider it a donation, if not please lets have your comments! The recursive pow() inspired my first attempt which looks pretty good to me but if you see an improvement feel free. I have attempted to make an iterative version. I wondered if there were some obvious ways of making it more concise. B) An answer to the malloc query in comments in the code (after 'int stack;') would be helpful too. Perhaps considering the following will show what I mean better... slightly different scenario to the main code appended, here im looking at strings. if you have:- binstr ="101010101010101010....010101001111111" and a function binstr_to_intstr() to create:- intstr ="125663....137373077" assuming you could fit intstr into an int and used pr_numi, how would you accurately calculate the size of array needed based on the size of binstr? How would you declare/allocate/use the array/memory/pointer? stack=77 stack=373 stack=137 ... stack[n-1]=663 stack[n]=125 */ /*--------------------start of code---------------*/ #include #include #include #define PR(x) printf(#x " = %d ",x) #define NL putchar('\n') #define SP putchar(' ') #define DELIM "," #define iabs(x) ( (x)>0?(x):-(x) ) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* recursive version...*/ void pr_numr( int x) { if (iabs(x)<1000) printf("%3d", x); else { pr_numr(x/1000); printf(DELIM "%03d", iabs(x%1000)); } return; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* iterative version...*/ void pr_numi( int x) { int stack; /*the '3' should be related to sizeof(int) (i.e. one less than?) or some formula with lots of nice shifts?, use malloc?*/ int i=0; if (iabs(x)<1000) printf("%3d", x); else { do { stack[i++] =x%1000; x/=1000; } while (iabs(x)>1000); printf("%3d", x); while(--i>=0) printf(DELIM "%03d", iabs(stack[i])); } return; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int main(int argc, char **argv) { int x, i,m,t[] = {0, 1, 12, 123, 999,1000, 1234, 1034, 12034, 12009880, 1123034783, INT_MAX}; m= sizeof(t)/sizeof(int); if (argc==1) for(i=0;i0) { printf("%20d: ", atol(*++argv)); pr_numr(atol(*argv)); printf("\n%20s ", " "); pr_numi(atol(*argv)); NL; } return 0; } /*--------------------end of code-----------------*/ Nov 13 '05 #1 