[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 195
  • Last Modified:

Formatting Time

I am trying to write a function called FormatTime() that takes a single parmater that is a time in seconds and then return a string that represents the time in the following format: hh:mm:ss.

Below is what I have so far.  I am unsure of how to convert a int into a string and also to account for the space when there is only one digit in a location.  For example: 02:20:06.  

#include <iostream>
#include <string>
#include <complex>
#include <iomanip>
using namespace std;

int main(){

int InputSeconds;
int     hours = (InputSeconds/3600);
int minutes = ((InputSeconds%3600)/60);
int seconds = ((InputSeconds%3600)%60);

return 0;

//int FormatTime (int     hours, int minutes, int seconds)
//int InputTimeTotal;
//int     hours = (int seconds/3600);
//int minutes = ((InputTimeTotal%3600)/60);
//int seconds = ((InputTimeTotal%3600)%60);
//return hours;
//return minutes;
//return seconds;

//int main(){
//int hh, mm, ss;
//int result;
//result= FormatTime(hh, mm, ss);

//return 0;
1 Solution
Your best bet is to do cout.fill('0'); and cout.width(2); before you start outputting the numbers.

That will set minimum 2 digits and leading 0 if the value is less than 10.

int hour = 13;
int min = 6;
int sec = 2;

// will print 13:06:02
cout << hour << ':' << min << ':' << sec;

If you want to do it really nice you save the return values from those functions. They are the old values:

char oldfill = cout.fill('0');
int oldw = cout.width(2);
cout << .... ;

This will restore the stream to the old values.


Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now