Printing leading 0's in C?

2019-01-01 03:31发布

I'm trying to find a good way to print leading 0's, such as 01001 for a zipcode. While the number would be stored as 1001, what is a good way to do it?

I thought of using either case statements/if then to figure out how many digits the number is and then convert it to an char array with extra 0's for printing but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.

标签: c printf
10条回答
梦寄多情
2楼-- · 2019-01-01 04:11

Zipcode is a highly localised field, many countries have characters in their postcodes, e.g., UK, Canada. Therefore in this example you should use a string / varchar field to store it if at any point you would be shipping or getting users/customers/clients/etc from other countries.

However in the general case you should use the recommended answer (printf("%05d", number);).

查看更多
琉璃瓶的回忆
3楼-- · 2019-01-01 04:14

If you need to store the zipcode in a character array zipcode[] , you can use this:

snprintf( zipcode, 6, "%05.5d", atoi(zipcode));
查看更多
情到深处是孤独
4楼-- · 2019-01-01 04:15

You place a zero before the minimum field width:

printf("%05d",zipcode);
查看更多
只靠听说
5楼-- · 2019-01-01 04:21

More flexible.. Here's an example printing rows of right-justified numbers with fixed widths, and space-padding.

//---- Header
std::string getFmt ( int wid, long val )
{  
  char buf[64];
  sprintf ( buf, "% *ld", wid, val );
  return buf;
}
#define FMT (getFmt(8,x).c_str())

//---- Put to use
printf ( "      COUNT     USED     FREE\n" );
printf ( "A: %s %s %s\n", FMT(C[0]), FMT(U[0]), FMT(F[0]) );
printf ( "B: %s %s %s\n", FMT(C[1]), FMT(U[1]), FMT(F[1]) );
printf ( "C: %s %s %s\n", FMT(C[2]), FMT(U[2]), FMT(F[2]) );

//-------- Output
      COUNT     USED     FREE
A:      354   148523     3283
B: 54138259 12392759   200391
C:    91239     3281    61423

The function and macro are designed so the printfs are more readable.

查看更多
登录 后发表回答