-3

I was writing a c++ program that converts time into: hours, minutes, and seconds.
What I need to do is to convert time into the form of: HH:MM:SS, anyways
here is my code:

#include <iostream>
using namespace std;

int main() {
    long time, hour, min, sec;
    cout<<"Enter elapsed time: ";
    cin>>time;
    cout<<time;
    hour = time/3600;
    min = (time%3600) / 60;
    sec = (time%3600) % 60;
    cout<<"\nIn HH:MM:SS -> ";
    cout<<hour<<":"<<min<<":"<<sec;
    return 0;
}


When I enter time in example: 3600, it displays 1:0:0 unlike the form I'm looking forward, so I need it to be displayed as "01:00:00" in this form. What should I do?

Adam Hussein
  • 75
  • 5
  • 12
  • @scohe001 That's not a duplicate. My question is different. – Adam Hussein Jan 17 '18 at 22:08
  • 5
    Your question seems to be asking for a way to ensure the number of digits for Hours/Min/Sec are the same by padding 0's. Can you explain why the other question is different from yours? – scohe001 Jan 17 '18 at 22:10
  • It's not a good idea to write your own times; instead you should use something like [`std::put_time`](http://en.cppreference.com/w/cpp/io/manip/put_time) if possible. I'm not sure exactly how to use that or this would be an answer, but a lot can go wrong if you try to do it yourself. See https://youtu.be/QCwpVtqcqNE for an example of when this can go wrong. – Daniel H Jan 17 '18 at 22:17
  • @scohe001 Why do I get downvotes, explain please? – Adam Hussein Jan 17 '18 at 22:28
  • I can't speak for everyone else, but I downvoted because you weren't able to distinguish your question from the one I posted. As such, it looks like you didn't put in the effort to research this problem before you posted (see http://idownvotedbecau.se/noresearch/ for more info). I'm always willing to change my vote if you can prove me wrong though! :) – scohe001 Jan 17 '18 at 22:45

1 Answers1

1

Include <iomanip> and use std::setfill and std::setw to define what character you want to use to fill and what is the width of the field to be printed.

std::cout << std::setfill('0') << std::setw(2) << hour << ":"; 
std::cout << std::setfill('0') << std::setw(2) << min << ":" 
std::cout << std::setfill('0') << std::setw(2) << sec;
FrankS101
  • 2,112
  • 6
  • 26
  • 40