0

My function turns seconds to minutes. The problem is, if I have a number where the remainder is less than 10, it will just give give me remainder without a 0 before the remainder.

For example,

  • 368 seconds would just turn to 6:8
  • 360 would turn to 6:0
  • 361 to 6:1

I would like

  • 368 seconds to turn to 6:08
  • 360 to 6:00
  • 361 to 6:01
void toMinutesAndSeconds(int inSeconds, int &outMinutes, int &outSeconds) {
    outMinutes = inSeconds / 60;
    outSeconds = inSeconds % 60;
}

I'm outputting to a text file.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Do you output minutes/seconds to console? If so, how do you do that? – zhm Mar 21 '17 at 02:24
  • You want to "pad" the number with zeroes. Search for zero-padding. (or prefixing) – Disillusioned Mar 21 '17 at 02:38
  • Possible duplicate of [How can I pad an int with leading zeros when using cout << operator?](http://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator) – Zze Mar 21 '17 at 04:49
  • The code you've shown is correct. The problem is in the code you haven't shown, i.e., in the code that **converts** the numeric value to text. – Pete Becker Mar 21 '17 at 13:15

1 Answers1

2

That's a matter of how you output your values. That value itself doesn't have "leading zeros".

#include <iostream>
#include <iomanip>

void toMinutesAndSeconds(int inSeconds, int &outMinutes, int &outSeconds) 
{
    outMinutes = inSeconds / 60;
    outSeconds = inSeconds % 60;
}

int main() 
{
    int minutes = 0;
    int seconds = 0;
    toMinutesAndSeconds(368, minutes, seconds);
    std::cout << std::setfill('0') << std::setw(2) << minutes << ":"
        << std::setfill('0') << std::setw(2) << seconds;
    return 0;
}

prints

06:08
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71