C99 printf 中的变量前导零 [英] Variable leading zeroes in C99 printf

查看:67
本文介绍了C99 printf 中的变量前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C99 编写一个多精度库.根据编译我的代码的平台,我选择了不同的表示基础.

I'm writing a Multiprecision Library in C99. Depending on which platform my code is compiled I am selecting a different Base of representation.

例如,假设在平台 X 上,系统选择 BASE=100;并且在平台 Y BASE=10000 上;

So, for instance, let's say that on platform X the system select BASE=100; and on platform Y BASE=10000;

假设我代表 big unsigned int 如下:

Let's say I'm representing big unsigned int as follow:

typedef struct a {
       big_enough_uint *digits;
       unsigned int length;
       unsigned int last;
} bigUint;

所以当我在 BASE-100 系统上时,我希望我的打印功能是

So when i'm on BASE-100 system I want my print function to be

void my_print(bigUint *A){
     unsigned int i=0;

     fprintf(stdout,"%d",A->digits[0]);
     if(i!= A->last){
          for(;i<=A->last;i++)
                fprintf(stdout,"%02d",A->digits[i]);
     }
     printf(stdout,"\n");
}

在 BASE-10000 系统上,我希望它像这样

While on BASE-10000 systems I want it to be something like

void my_print(bigUint *A){
     unsigned int i=0;

     fprintf(stdout,"%d",A->digits[0]);
     if(i!= A->last){
          for(;i<=A->last;i++)
                fprintf(stdout,"%04d",A->digits[i]);
     }
     printf(stdout,"\n");
}

我为什么要这样做??

假设我有以下号码:

12345600026789

在 BASE-100 表示中,数字数组将是(小端形式):

In BASE-100 representation the digits array will be (little-endian form):

12|34|56|0|2|67|89
         ^ ^ I want ONE LEADING ZEROES

在 BASE-10000 中:

while in BASE-10000:

12|3456|2|6789
        ^ I want THREE LEADING ZEROES

有没有简单的方法可以做到这一点?

Is there a simple way to do that?

推荐答案

阅读 man printf 中字段宽度的 * 占位符.

Read about the * place holder for the field width in man printf.

printf("%0*d", 3, 42);

给予

042

printf("% *s", 42, "alk");

给予

<39 spaces>alk

这篇关于C99 printf 中的变量前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆