Question

In: Computer Science

Write a c++ program that inputs a time from the console. The time should be in...

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?

Solutions

Expert Solution

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;
}


Related Solutions

PLease use c++ Write a checkbook balancing program. The program will read in, from the console,...
PLease use c++ Write a checkbook balancing program. The program will read in, from the console, the following for all checks that were not cashed as of the last time you balanced your checkbook: the number of each check (int), the amount of the check (double), and whether or not it has been cashed (1 or 0, boolean in the array). Use an array with the class as the type. The class should be a class for a check. There...
Write a program in C (NOT C++ or C#) The program inputs 5 elements into each...
Write a program in C (NOT C++ or C#) The program inputs 5 elements into each of 2 integer arrays. Multiply corresponding array elements, that is, arrayOne[0] * arrayTwo[0], etc. Save the product into a third array called prodArray[ ]. Display the product array.
Write a program that inputs the values of three Boolean variables, a, b, and c, from...
Write a program that inputs the values of three Boolean variables, a, b, and c, from a “cin” operator (user gives the values be sure to prompt user for what they have to give!). Then the program determines the value of the conditions that follow as true or false. 1. !(a&&b&&c) && ! (a||b||c) 2. !(a||b)&&c Output should include the values of a,b,c ie 0 or 1 in the patterns that follow reflecting the Boolean logic being tested. Where “True”...
Write a C++ program, falling.cpp, that inputs a distance in meters from the user and computes...
Write a C++ program, falling.cpp, that inputs a distance in meters from the user and computes the amount of time for the object falling from that distance to hit the ground and the velocity of the object just before impact. Air resistance is discounted (assumed to fall in a vacuum). To compute the time, use the formula: t = Square Root (2d / g) where d is the distance in meters and g is the acceleration due to gravity on...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user to enter the three examinations ( test 1, test 2, and test 3), homework, and final project grades then calculate and display the overall grade along with a message, using the selection structure (if/else). The message is based on the following criteria: “Excellent” if the overall grade is 90 or more. “Good” if the overall grade is between 80 and 90 ( not including...
Write a checkbook balancing program. The program will read in, from the console, the following for...
Write a checkbook balancing program. The program will read in, from the console, the following for all checks that were not cashed as of the last time you balanced your checkbook: the number of each check (int), the amount of the check (double), and whether or not it has been cashed (1 or 0, boolean in the array). Use an array with the class as the type. The class should be a class for a check. There should be three...
Write a C++ program that inputs (cin) a word from the keyboard and generates several different...
Write a C++ program that inputs (cin) a word from the keyboard and generates several different scrambles of the word without using vectors. The input word can be from 4 to 10 letters in length. The number of scrambles produced depends on the number of letters in the word. e.g. the 4 letter word “lose” would have 4 different scrambles produced and the seven letter word “edition” would have seven different scrambles. Here is a candidate example:      Input: FLOOR...
I need this written in C # ASAP Write a C# console program that continually asks...
I need this written in C # ASAP Write a C# console program that continually asks the user "Do you want to enter a name (Y/N)? ". Use a "while" loop to accomplish this. As long as the user enters either an upper or lowercase 'Y', then prompt to the screen "Enter First and Last Name: " and then get keyboard input of the name. After entering the name, display the name to the screen.
1. Write a program in C++ that takes as inputs a positiveinteger n and a...
1. Write a program in C++ that takes as inputs a positive integer n and a positive double a. The function should compute the geometric sum with base a up to the powern and stores the result as a protected variable. That is, the sum is: 1 + ? + ? ^2 + ? ^3 + ? ^4 + ⋯ + ? ^?2.  Write a program in C++ that takes as input a positive integer n and computes the following productsum...
Write a C# console program that fills the right to left diagonal of a square matrix...
Write a C# console program that fills the right to left diagonal of a square matrix with zeros, the lower-right triangle with -1s, and the upper left triangle with +1s. Let the user enter the size of the matrix up to size 21. Use a constant and error check. Output the formatted square matrix with appropriate values. Refer to the sample output below. Sample Run: *** Start of Matrix *** Enter the size of square (<= 21): 5 1 1...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT