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 03:58

The correct solution is to store the zip code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.

A number is a thing you do arithmetic on. A zip code is not that.

查看更多
萌妹纸的霸气范
3楼-- · 2019-01-01 04:03
sprintf(mystring, "%05d", myInt);

Here, "05" says "use 5 digits with leading zeros".

查看更多
闭嘴吧你
4楼-- · 2019-01-01 04:05
printf("%05d", zipCode);

查看更多
步步皆殇っ
5楼-- · 2019-01-01 04:06

If you are on a *NIX Machine:

man 3 printf

This will show a manual page, similar to:

0 The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined.

Even though the question is for C, this page may be of aid.

查看更多
若你有天会懂
6楼-- · 2019-01-01 04:08

printf allows various formatting options.

ex:

printf("leading zeros %05d", 123);
查看更多
笑指拈花
7楼-- · 2019-01-01 04:09

You will save yourself a heap of trouble (long term) if you store a zip code as a character string, which it is, rather than a number, which it is not.

查看更多
登录 后发表回答