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?
|
2 answers
According to the comment @pavel , of course, the easiest option that comes to mind:
cout << 0 << value;
Example: ideone
It is possible through C-shnuyu
printf
function:int dd = 1, mm = 9, yy = 1; printf("%02d - %02d - %04d", mm, dd, yy);
Example: ideone
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
Using
<iomanip>
:cout << setfill('0') << setw(2) << 5;
Example: ideone
- oneor 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; } }
|
printf("%05d",value);
? - pavel