用C / C ++打印前导空格和零

我需要在数字前打印一些前导空格和零,以便输出如下:

00015 22 00111 8 126 

在这里,我需要在数字为even时打印leading spaces ,在oddleading zero

我是这样做的:

 int i, digit, width=5, x=15; if(x%2==0) // number even { digit=log10(x)+1; // number of digit in the number for(i=digit ; i<width ; i++) printf(" "); printf("%d\n",x); } else // number odd { digit=log10(x)+1; // number of digit in the number for(i=digit ; i<width ; i++) printf("0"); printf("%d\n",x); } 

有没有捷径可以做到这一点?

要打印leading space and zero您可以使用:

 int x = 119, width = 5; // Leading Space printf("%*d\n",width,x); // Leading Zero printf("%0*d\n",width,x); 

所以在你的程序中只需更改:

 int i, digit, width=5, x=15; if(x%2==0) // number even printf("%*d\n",width,x); else // number odd printf("%0*d\n",width,x);