How to print commas manually in C

1 Answer

0 votes
#include <stdio.h>

// solution that works everywhere, 

void print_with_commas(size_t n) {
    char buf[32] = "";
    char out[48] = "";
    int len = sprintf(buf, "%zu", n);
    int out_i = sizeof(out) - 1;
    out[out_i--] = '\0';

    int count = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (count == 3) {
            out[out_i--] = ',';
            count = 0;
        }
        out[out_i--] = buf[i];
        count++;
    }

    printf("%s", &out[out_i + 1]);
}

int main() {
    size_t buffer_size = 2 * (size_t)(1ULL << 40); // 2 TB
    
    printf("buffer_size = ");
    print_with_commas(buffer_size);
    printf(" bytes\n");
}



/*
run:

buffer_size = 2,199,023,255,552 bytes

*/

 



answered May 2 by avibootz
...