Need help with formatting a clock
Nov 24, 2013 at 10:38pm UTC
I had to create a program which asks you to set a clock, then add minutes to it and update it according to how many minutes. I have everything done except for the formatting, like if it was 2:30 and someone added 35 minutes, it would show 3:5.
How can I correct the formatting?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include <iostream>
using namespace std;
struct clock {
short hour;
short minute;
};
clock setClock (short hour, short minute);
void addMinutes (short & minutes);
void displayClock (clock myClock);
int main () {
short minute = 0;
clock myClock;
myClock = setClock (12,0);
addMinutes (minute);
cout << myClock.hour << ":" << myClock.minute << endl;
cout << minute << endl;
myClock.minute = minute + myClock.minute;
displayClock (myClock);
return 0;
}
//---------------------------------------------------------------------
clock setClock (short hour, short minute){
clock temp;
cout << "Enter hour based on 12 hour clock: " ;
cin >> temp.hour;
cout << "Enter minute: " ;
cin >> temp.minute;
while (temp.hour > 12 || temp.minute > 60) {
cout << "The clock will be set to 12:00 due to incorrect entry." << endl;
temp.hour = 12;
temp.minute = 0;
}
return temp;
}
//---------------------------------------------------------------------
void addMinutes (short & minutes){
cout << "How many minutes do you wish to add to the current time?" ;
cin >> minutes;
}
//---------------------------------------------------------------------
void displayClock (clock myClock){
while ( myClock.minute > 59 ) {
myClock.minute = myClock.minute - 60;
myClock.hour = myClock.hour + 1;
}
while ( myClock.hour > 12 ) {
myClock.hour = myClock.hour - 12;
}
cout << myClock.hour << ":" << myClock.minute << endl;
}
Nov 24, 2013 at 10:45pm UTC
You could check if the number of minutes is less than 10, and if it is, print a 0 first before printing the minutes.
Nov 24, 2013 at 10:47pm UTC
That was a stunningly simple fix that I overlooked. :/ I was looking at cout.fill / cout.width. Do you perhaps know how to explain how to use that?
Nov 24, 2013 at 11:30pm UTC
Nevermind, figured it out.
1 2 3 4 5
cout << myClock.hour << ":" ;
cout.setf(ios::right);
cout.fill('0' );
cout.width(2);
cout << myClock.minute << endl;
Topic archived. No new replies allowed.