0

Alright, so I had an assignment in c++ where the user was to input a day and if the day was less than 10, the program would have to output a 0 in front of it. If the day was greater than 10, the program would output the day. An example would be if the user inputs 5, the program would output 05. If the user inputs 24, the program would output 24. My question is how do we define the 0 in front of the 5. This is the snippet of code of which I attempted but to no avail.

if (day < 10){
            f = 0 << day;
        }
            else {
            f = day;
        }

This is the statement I'm struggling with: f = 0 << day;

Any help would be great.

Thanks.

  • What is `f` exactly? And what do you think `0 << day` does? – David Schwartz Jul 20 '21 at 04:24
  • You could use formatting specifier with cout to tell it to pad out the value with a leading zero if required. – Andrew Truckle Jul 20 '21 at 04:32
  • https://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator – Andrew Truckle Jul 20 '21 at 04:35
  • 1
    Does this answer your question? [How can I pad an int with leading zeros when using cout << operator?](https://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator) – dwcanillas Jul 20 '21 at 05:22

2 Answers2

1

You can simply write:-

if(day<10)
{
 cout<<"0"<<day;
}
else cout<<day;

If you have any queries, please let me know

sushruta19
  • 327
  • 3
  • 12
1

Use printf to format your output

Ex:

printf("%02d", day);
Nishuthan S
  • 1,538
  • 3
  • 12
  • 30
funkunux
  • 11
  • 2