Display an integer comma seperated in C? -
this question has answer here:
how can display integer comma separated in c?
for example if int i=9876543
, result should 9,876,543.
you can play lc_numeric
, setlocale()
or build own function, like:
#include <stdio.h> #include <stdlib.h> char *fmt(long x) { char s[64], *p = s, *q, *r; int len; len = sprintf(p, "%ld", x); q = r = malloc(len + (len / 3) + 1); if (r == null) return null; if (*p == '-') { *q++ = *p++; len--; } switch (len % 3) { { *q++ = ','; case 0: *q++ = *p++; case 2: *q++ = *p++; case 1: *q++ = *p++; } while (*p); } *q = '\0'; return r; } int main(void) { char *s = fmt(9876543); printf("%s\n", s); free(s); return 0; }
Comments
Post a Comment