In: Computer Science
Write a c++ program that inputs a time from the console. The time should be in the format “HH:MM AM” or “HH:MM PM”. Hours may be one or two digits. Your program should then convert the time into a four-digit military time based on a 24-hour clock.
Code:
#include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string input; cout << "Enter (HH:MM XX) format time: "; getline(cin, input); int h, m; bool am; int len = input.size(); char a=toupper(input.at(len-2)), b = toupper(input.at(len-1)); if(a=='A' && b == 'M') { am = true; } else { am = false; } h = input.at(0) - '0'; if(input.at(1) == ':') { input = input.substr(2); } else { h = 10*h + (input.at(1) - '0'); input = input.substr(3); } m = input.at(0) - '0'; if(input.at(1) != ' ') { m = 10*m + (input.at(1) - '0'); } // 12AM means midnight, 12PM means afternoon if(h == 12) { h = 0; } if(!am) { h += 12; } cout << setw(2) << std::setfill('0') << h << m << " hours" << endl; }
Is there any easier way and a simpler way to write the code other than the above code?
This is one of the possible solutions. Anyway above code also looks fine.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string convertToMilitaryTime(string time)
{
//gets colon and space position in the
// given time string
int colon = time.find(':');
int space = time.find(' ');
//extracts hours, minutes and meredian strings from
the
// input time string
string hh = time.substr(0, colon);
string mm = time.substr(colon+1, space-colon-1);
string mer = time.substr(space+1);
//converts hours from string format to integer
int hours = atoi(hh.c_str());
// updating hours based on meredian
if(mer == "PM" &&hours != 12)
hours = hours + 12;
else if ( mer == "AM" &&hours == 12)
hours = 0;
//placing leading zero in hours if hour is one digit
if( hours >= 0 &&hours <= 9)
hh = "0";
else
hh = "";
//converring modified hours to string format
char H[5];
hh += itoa(hours,H,10) ;
//returns required output string
return hh + mm + " hours";
}
// main function
int main()
{
// inputs time in the form hh:mm AM/PM
string time;
cout << "Enter time (HH:MM AM) or (HH:MM PM): ";
getline(cin,time,'\n');
//calls convertToMilitaryTime to conevert the given
//time into military time
string milTime = convertToMilitaryTime(time);
//displays to the console
cout << milTime << endl;
return 0;
}