跨平台支持 sprintf 的格式 '-Flag

Cross Platform Support for sprintf's Format '-Flag

Single UNIX Specification Version 2sprintf 的格式 ' 标志行为指定为:

The integer portion of the result of a decimal conversion (%i, %d, %u, %f, %g or %G) will be formatted with thousands' grouping characters[1]

我在 or the specifications. g++ even warns:

中找不到格式 '-flag

ISO C++11 does not support the ' printf flag

该标志在 Visual C 中甚至无法识别以发出警告; printf("%'d", foo) outputs:

'd

我希望能够编写使用 '-标志格式行为的符合 C 标准的代码。因此,我正在寻找以下答案之一:

  1. C-格式的标准规范'-flag
  2. gcc 格式 '-flag
  3. 的跨平台兼容外推
  4. 证明跨平台外推是不可能的

标准 C 不直接提供格式化功能,但它确实提供了在特定于语言环境的基础上检索格式应该是什么的规范的能力。因此,由您来检索语言环境的正确格式规范,然后将其用于格式化您的数据(但即便如此,它也有些不平凡)。例如,这里有一个格式化 long 数据的版本:

#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <limits.h>

static int next_group(char const **grouping) {
    if ((*grouping)[1] == CHAR_MAX)
        return 0;
    if ((*grouping)[1] != '[=10=]')
        ++*grouping;
    return **grouping;
}

size_t commafmt(char   *buf,            /* Buffer for formatted string  */
                int     bufsize,        /* Size of buffer               */
                long    N)              /* Number to convert            */
{
    int i;
    int len = 1;
    int posn = 1;
    int sign = 1;
    char *ptr = buf + bufsize - 1;

    struct lconv *fmt_info = localeconv();
    char const *tsep = fmt_info->thousands_sep;
    char const *group = fmt_info->grouping;
    // char const *neg = fmt_info->negative_sign;
    size_t sep_len = strlen(tsep);
    size_t group_len = strlen(group);
    // size_t neg_len = strlen(neg);
    int places = (int)*group;

    if (bufsize < 2)
    {
ABORT:
        *buf = '[=10=]';
        return 0;
    }

    *ptr-- = '[=10=]';
    --bufsize;
    if (N < 0L)
    {
        sign = -1;
        N = -N;
    }

    for ( ; len <= bufsize; ++len, ++posn)
    {
        *ptr-- = (char)((N % 10L) + '0');
        if (0L == (N /= 10L))
            break;
        if (places && (0 == (posn % places)))
        {
            places = next_group(&group);
            for (int i=sep_len; i>0; i--) {
                *ptr-- = tsep[i-1];
                if (++len >= bufsize)
                    goto ABORT;
            }
        }
        if (len >= bufsize)
            goto ABORT;
    }

    if (sign < 0)
    {
        if (len >= bufsize)
            goto ABORT;
        *ptr-- = '-';
        ++len;
    }

    memmove(buf, ++ptr, len + 1);
    return (size_t)len;
}

#ifdef TEST
#include <stdio.h>

#define elements(x) (sizeof(x)/sizeof(x[0]))

void show(long i) {
    char buffer[32];

    commafmt(buffer, sizeof(buffer), i);
    printf("%s\n", buffer);
    commafmt(buffer, sizeof(buffer), -i);
    printf("%s\n", buffer);
}


int main() {

    long inputs[] = {1, 12, 123, 1234, 12345, 123456, 1234567, 12345678 };

    for (int i=0; i<elements(inputs); i++) {
        setlocale(LC_ALL, "");
        show(inputs[i]);
    }
    return 0;
}

#endif

这确实有一个错误(但我认为这个错误很小)。在二进制补码硬件上,它不会正确转换最大负数,因为它试图将负数转换为其等效的正数 N = -N; 在二进制补码中,最大负数没有对应的正数,除非您将其提升为更大的类型。解决这个问题的一种方法是将数字提升为相应的无符号类型(但这有点不平凡)。

对其他整数类型实施相同的操作非常简单。对于浮点类型,需要做更多的工作。正确转换浮点类型(即使没有格式化)对他们来说已经足够了,我至少会考虑使用 sprintf 之类的东西来进行转换,然后将格式插入到生成的字符串中。