'Convert 1 to 01 in C++ without using function
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.
Solution 1:[1]
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
Solution 2:[2]
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';
}
Solution 3:[3]
maybe:
std::cout << ((a <= 9) ? 0 : "") << a;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Henri Menke |
| Solution 3 |
