Printing leading 0's in C?

前端 未结 10 1277
[愿得一人]
[愿得一人] 2020-11-22 17:26

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

相关标签:
10条回答
  • 2020-11-22 17:54

    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.

    0 讨论(0)
  • 2020-11-22 17:57

    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.

    0 讨论(0)
  • 2020-11-22 18:05

    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);).

    0 讨论(0)
  • 2020-11-22 18:06

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

    snprintf( zipcode, 6, "%05.5d", atoi(zipcode));
    
    0 讨论(0)
提交回复
热议问题