-2
int a;
std::cout<<"Enter hour: ";
std::cin>>a;
std::cout<< a;

This is just for question purpose. Is there any trick to output 01 instead of 1 without using a function? Suppose if the input is 9 I want 09 to be an output but if the 'a' is 2 digit there is no need to add 0.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Bibek
  • 11
  • 1
  • 4

4 Answers4

4

I think you want:

std::cout << std::setw(2) << std::setfill('0') << a;

This sets the field width to 2 and the fill character to '0'. Keep in mind, however, that although the field width is reset after outputting a, the fill is not. So if this is temporary, be sure to save the fill before setting it.

BTW these function are in "iomanip" library

Community
  • 1
  • 1
md5i
  • 3,018
  • 1
  • 18
  • 32
0

maybe:

std::cout << ((a <= 9) ? 0 : "") << a;
0

You could use the fine Boost.Format library to format the output with printf-like syntax.

#include <boost/format.hpp>
#include <iostream>

int main()
{
    std::cout << boost::format("%02d") % 1 << '\n';
}
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
0

You can use:

#include <iomanip>
ans=1;
cout<<setw(2)<<setfill('0')<<ans<<endl;

OUTPUT: 01