Originally Posted by
nonoob
Code:
void insert_commas(char *inp, char *outp) {
int a = (21 - (int)strlen(inp)) % 3, d;
for (; outp[ d = a / 3] = *inp++; a += 4)
outp[d + 1] = ',';
outp[d - 1] = '\0'; }
...
char buffer[100], buffer2[100];
int number = -1234567153;
sprintf(buffer, "%d", number);
insert_commas(buffer, buffer2);
printf("\"%s\"", buffer2);
Outputs "-1,234,567,153"
Good and standard solution.
It is a bit slow due to the use of standard functions
like sprintf().
I elaborated 10 million cycles in 5,262 clock ticks:
Code:
-1,234,567,153
Elapsed time = 5,262
Press any key to continue...
after inserting the missing code:
Code:
//-----------------------------------
// comma_sep.c
//-----------------------------------
// version proposed by nonoob
//-----------------------------------
#include <stdio.h>
#include <string.h>
#include <time.h>
void insert_commas(char *inp, char *outp) {
int a = (21 - (int)strlen(inp)) % 3, d;
for (; outp[ d = a / 3] = *inp++; a += 4)
outp[d + 1] = ',';
outp[d - 1] = '\0';
}
int main(void){
int times = 10000000; // iterations to test
int x = 0;
char buffer[100], buffer2[100];
int number = -1234567153; // number to format
clock_t start = 0; // initial time
clock_t stop = 0; // end time
start = clock();
for (x = 0; x < times; x++){
sprintf(buffer, "%d", number);
insert_commas(buffer, buffer2);
}
stop = clock();
int elapsed = (int)(stop-start);
printf("%s\n", buffer2);
sprintf(buffer,"%d",elapsed);
insert_commas(buffer, buffer2);
printf("\n Elapsed time = %s\n",buffer2);
return 0;
}