Padding printf for Strings by 0

后端 未结 3 1097
心在旅途
心在旅途 2021-01-12 21:33

Is there a way to replace the space character to 0 in printf padding for field width

Code used

printf(\"%010s\",\"this\");

Doesnt s

3条回答
  •  死守一世寂寞
    2021-01-12 22:09

    Indeed, the 0 flag only works for numeric conversions. You will have to do this by hand:

    int print_padleftzeroes(const char *s, size_t width)
    {
        size_t n = strlen(s);
        if(width < n)
            return -1;
        while(width > n)
        {
            putchar('0');
            width--;
        }
        fputs(s, stdout);
        return 0;
    }
    

提交回复
热议问题