Proper format for displaying time

May 17, 2010 at 12:03am
I'm coding a program to add and subtract time from a user given time. The problem I've run into is that I have the hours and minutes in int form. I need to display the minutes as 00.. 09. If I enter them as 00 they still come out as 0. How do you format you integer output to have two significant figures?
May 17, 2010 at 12:08am
For output, you need to #include <iomanip> and use some of the proper manipulators.

For input, the istream doesn't care how many zeros you have in front of a number, so long as you set it to read decimal (or whatever) numbers.

Hope this helps.
May 17, 2010 at 12:11am
Hi. This sounds interesting but you haven't provided much information. Maybe you should include some of the code and point out exactly what you're trying to do. I think maybe you want the hours to be integers and the minutes to include a decimal. That's why I'm interested. Not to say it's not worth responding just to try to help. So try to add more info, please.
May 17, 2010 at 12:24am
Well, I don't need decimals, I just need the numbers 1-9 to display zeros before them so that the time would be 5:03 instead of 5:3.

There's more to my code (error checks and such) but a simplified version is:


1
2
3
4
5
cout<<"Enter the current Hour: ";
cin >> hour;
cout << "Enter the current Minutes: ";
cin >> minute;
cout << "Initial time is: " << hour << ":" << minute << endl;


All I need to know is how to set the output to display two figures all the time.

From Duoas post I though maybe I could use something like:

1
2
3
4
5
if (minute < 10 && min > 0)
{
cout << setfill ('0') << setw (1);
cout << minute;
}


Do I have other options or is that going to be the simplest one?
May 17, 2010 at 12:30am
One simple solution could be:

if(minute >= 0 && minute < 10)
cout << '0' << minute;
else
cout << minute;

I did it for a school assignment recently. I don't know much, but I'm pretty confident saying that you shouldn't make things more complicated then they need to be. That's all.
May 17, 2010 at 12:36am
@dragonbane You are doing it right. You just need to setw(2) rather than 1

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

Topic archived. No new replies allowed.