显示以C分隔的整数逗号? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我们如何在C中显示分隔的整数逗号?

例如,如果int i=9876543,结果应该是9,876,543.

c
2个回答
3
投票

你可以玩LC_NUMERICsetlocale()或建立自己的功能,如:

#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) {
        do {
            *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;
}

0
投票

我相信没有内置功能。但是,您可以将整数转换为字符串,然后根据结果字符串的长度计算逗号位置(提示:第一个逗号将在strlen(s)%3数字之后,避免使用逗号)。

© www.soinside.com 2019 - 2024. All rights reserved.