Printing leading 0's in C?

前端 未结 10 1407
[愿得一人]
[愿得一人] 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.

提交回复
热议问题