Answer to Question #178095 in C++ for Luna

Question #178095

Write a program that asks the user to input a start time and an end time. Your program needs to calculate the elapsed time. Here is a sample run(user’s input is shown in bold)

Sample run 1

Input start time: 4:15

Input end time: 5:05

The elapsed time is 0 hours & 50 minutes.


Sample run 2

Input start time: 11:50

Input end time: 16:05

The elapsed time is 4 hours & 15 minutes.



1
Expert's answer
2021-04-03T17:54:35-0400
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s1, s2;
    int h1, h2, m1, m2, hours, minutes;
    cout<<"Input start time: ";
    cin>>s1;
    cout<<"Input end time: ";
    cin>>s2;
    h1 = stoi(s1.substr(0, s1.find(":")));
    m1 = stoi(s1.substr(s1.find(":") + 1, s1.length() - s1.find(":") - 1));
    h2 = stoi(s2.substr(0, s2.find(":")));
    m2 = stoi(s2.substr(s2.find(":") + 1, s2.length() - s2.find(":") - 1));
    hours = h2 - h1;
    minutes = m2 - m1;
    if(minutes < 0){
        hours -= 1;
        minutes += 60;
    }
    cout<<"The elapsed time is "<<hours<<" hours & "<<minutes<<" minutes.";
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS