How can you display a number from 0 to 9 in this form 00, 01, 02 , that is, so that zero is in front of a digit?

  • four
    printf("%05d",value); ? - pavel
  • 3
    @pavel is only 05 - it expands to 5 characters with zeros. - Vladimir Martyanov
  • one
    @pavel and besides this is a solution. - αλεχολυτ

2 answers 2

  1. According to the comment @pavel , of course, the easiest option that comes to mind:

     cout << 0 << value; 

    Example: ideone


  1. It is possible through C-shnuyu printf function:

     int dd = 1, mm = 9, yy = 1; printf("%02d - %02d - %04d", mm, dd, yy); 

    Example: ideone


  1. It is possible through sprintf :

     int dd = 1, mm = 9, yy = 1; char s[25]; sprintf(s, "%02d - %02d - %04d", mm, dd, yy); cout << s; 

    Example: ideone


  1. Using <iomanip> :

     cout << setfill('0') << setw(2) << 5; 

    Example: ideone

  • one
    or you can simply cout <<0<<value; - pavel
  • For some reason, @pavel didn’t think about the simplest and most logical variant) - Denis

Try this:

 #include <iostream> #include <iomanip> int main(){ for(int i = 0; i < 10; ++i){ std::cout << std::setw(2); std::cout << std::setfill('0'); std::cout << i << std::endl; } } 

std :: setw
std :: setfill