dimanche 8 décembre 2019

How to prefix an integer with 0 [duplicate]

I am making a clock from milliseconds

This is my code

int milliseconds = currentValue ;   
int seconds = milliseconds / 1000;
milliseconds %= 1000;
if (m_bShowMinutes)
{
    minutes = seconds / 60;
    seconds %= 60;
}    
if (m_bShowHours)
{
    hours = minutes / 60;
    minutes %= 60;
}    
if (m_bShowHours)
    strs << hours <<":";

if (m_bShowMinutes)
    strs << minutes << ":";

strs <<seconds<< ":"<< milliseconds;
std::string str = strs.str();
std::cout << str;

My question is that when time for minutes is between 0 - 9 i would want the int value to be prefixed by a 0 so the final output should look like 00:04:23:123, ofcourse i can convert the int to string check for the length and prefix 0.

Could there be a better way of doing this ?

Aucun commentaire:

Enregistrer un commentaire