Printing leading 0's in C?

前端 未结 10 1286
[愿得一人]
[愿得一人] 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:44

    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.

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

    You place a zero before the minimum field width:

    printf("%05d",zipcode);
    
    0 讨论(0)
  • 2020-11-22 17:47

    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.

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

    printf allows various formatting options.

    ex:

    printf("leading zeros %05d", 123);
    
    0 讨论(0)
  • 2020-11-22 17:50
    sprintf(mystring, "%05d", myInt);
    

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

    0 讨论(0)
  • 2020-11-22 17:52
    printf("%05d", zipCode);
    

    The 0 indicates what you are padding with and the 5 shows the length of the integer number. For example if you use "%02d" (Useful for dates) this would only pad zeros for numbers in the ones column ie.(06 instead of 6). Example 2, "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. ie. (number 7 padded to 007 and number 17 padded to 017).

    0 讨论(0)
提交回复
热议问题