In: Computer Science
I need program to calculate the number of seconds since
midnight.
For example, suppose the time is 1:02:05 AM.
Since there are 3600 seconds per hour and 60 seconds per
minutes,
it has been 3725 seconds since midnight (3600 * 1 + 2 * 60 + 5 =
3725).
The program asks the user to enter 4 pieces of information: hour,
minute, second, and AM/PM.
The program will calculate and display the number of seconds since
midnight.
Modify the program by adding error checking loops. Hour must be a
number from 1 to 12.
Minute and second must be numbers from 0 to 59. Also check whether
“AM” or “PM” is entered.
Every time an invalid value is entered,
display an error message and ask the user to re-enter a valid value
immediately.
[Hint: be very careful when the hour is 12].
The following is an example:
Enter hour: 0
Hour must be from 1 to 12.
Enter hour: 13
Hour must be from 1 to 12.
Enter hour: 12
Enter minute: -1
Minute must be from 0 to 59.
Enter minute: 60
Minute must be from 0 to 59.
Enter minute: 14
Enter second: -1
Second must be from 0 to 59.
Enter second: 60
Second must be from 0 to 59.
Enter second: 47
Enter AM or PM: FM
Please enter AM or PM
Enter AM or PM: PM
Seconds since midnight: 44087
#include <iostream> using namespace std; int readInt(int min, int max, string msg) { int x; cout << msg; cin >> x; while(x < min || x > max) { cout << "Value must be from " << min << " to " << max << "." << endl; cout << msg; cin >> x; } return x; } int main() { int h, m, s; string amPm; h = readInt(1, 12, "Enter hour: "); m = readInt(0, 59, "Enter minute: "); s = readInt(0, 59, "Enter second: "); cout << "Enter AM or PM:"; cin >> amPm; while(amPm != "AM" && amPm != "PM") { cout << "Please enter AM or PM" << endl; cout << "Enter AM or PM:"; cin >> amPm; } long seconds = 0; seconds += s; seconds += m * 60; if(h == 12) { h = 0; } seconds += h * 60 * 60; if(amPm == "PM") { seconds += 12 * 60 * 60; } cout << "Seconds since midnight: " << seconds << endl; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.