Convert Seconds Into HH:MM:SS Format C++
Feb 18, 2015 12:39 · 298 words · 2 minute read
This C++ program prompt the user to input the elapsed time for an event in seconds. The program outputs the elapsed time in hours, minutes, and seconds HH:MM:SS. It also outputs the input from the user.
/*
* This program will take an input of time in seconds and output it in HH:MM:SS format as well as the original time in seconds.
* By: Jesse
* Created 01/14/2015
*/
#include <iostream>
using namespace std;
int main() {
// Declare variable
//
int sec = 0;
int hrs = 0;
int mins = 0;
int secs = 0;
int n = 0;
// Request the user to enter the time in seconds
//
cout << "Enter elapsed time in seconds: ";
cin >> n;
// Sets seconds to n
//
sec = n;
// Checks if input is a negative number since we can't go back in time and stops the program.
//
if (sec < 0) {
cout << "Error: Sorry you can't turn back time!" << endl;
cout << "But if you could the elapsed time would be: " << hrs << ":" << mins << ":" << secs << endl;
system("pause");
return (0);
}
// Takes the seconds and calculates the hours, minutes, and seconds.
// 3600 seconds in 1 hour
// 60 seconds in 1 minute
//
hrs = sec / 3600;
sec = sec % 3600;
mins = sec / 60;
sec = sec % 60;
secs = sec;
// Outputs the seconds in the HH:MM:SS format then out puts the original time in seconds.
//
cout << "The elapsed time is: " << hrs << ":" << mins << ":" << secs << endl;
cout << "With the entered amount of " << n << " seconds." << endl;
system("pause");
return (0);
}