Write a C++ program that reads a time from the keyboard. The time should be in t
ID: 3690245 • Letter: W
Question
Write a C++ program that reads a time from the keyboard. The time should be in the format "HH:MM AM" or "HH:MM PM". Hours can be one or two digits, minutes are exactly two digits, and AM/PM can be in any mixture of uppercase and lowercase. For example, "1:10 am", "12:05 PM", and "12:45 aM" are valid inputs. Your program should include a function that takes a string parameter containing the time. This function should convert the time into a four-digit military time based on a 24-hour clock. For example, "1:10 AM" would output "0110 hours", "11:30 PM" would output "2330 hours", "12:15 AM" would output "0015 hours", and "5:05 Pm" would output "1705 hours". The function should return a string to be written to the screen by the main function.
Sample program runs are as follows, where user input is shown in red color:
Explanation / Answer
#include <iostream>
#include <stdio.h>
#include <string>
#include <cctype>
#include <stdlib.h>
#include <sstream>
using namespace std;
string itoa(int num)
{
stringstream converter;
converter << num;
return converter.str();
}
string convert(string str){
size_t pos = str.find_first_of(':');
string hour = str.substr(0,pos);
string min = str.substr(pos+1,2);
string ampm = str.substr(pos+4,2);
int h = atoi(hour.c_str())%12;
if(ampm == "pm" || ampm == "Pm" || ampm == "PM" || ampm == "pM")
hour = itoa(h+12);
else if(h == 0)
hour = "00";
else if(h<10)
hour = "0" + hour;
string mtime = hour + min;
return mtime;
}
int main() {
string ntime;
cout<<"Enter time: ";
getline(cin,ntime);
cout<<"Corresponding military time is "<<convert(ntime)<<" hours";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.