Formatting: how to convert 1 to “01”, 2 to “02”, 3 to "03", and so on

20k Views Asked by At

Following code outputs the values in time format, i.e. if it's 1:50pm and 8 seconds, it would output it as 01:50:08

cout << "time remaining: %02d::%02d::%02" << hr << mins << secs;

But what I want to do is (a) convert these ints to char/string (b) and then add the same time format to its corresponding char/string value.

I have already achieved (a), I just want to achieve (b).

e.g.

    char currenthour[10] = { 0 }, currentmins[10] = { 0 }, currentsecs[10] = { 0 };

    itoa(hr, currenthour, 10);
    itoa(mins, currentmins, 10);
    itoa(secs, currentsecs, 10);

Now if I output 'currenthour', 'currentmins' and 'currentsecs', it will output the same example time as, 1:50:8, instead of 01:50:08.

Ideas?

3

There are 3 best solutions below

2
On BEST ANSWER

If you don't mind the overhead you can use a std::stringstream

#include <sstream>
#include <iomanip>

std::string to_format(const int number) {
    std::stringstream ss;
    ss << std::setw(2) << std::setfill('0') << number;
    return ss.str();
}
0
On

As from your comment:

"I assumed, using %02 was a standard c/c++ practice. Am I wrong?"

Yes, you are wrong. Also c/c++ isn't a thing, these are different languages.

C++ std::cout doesn't support printf() like formatting strings. What you need is setw() and setfill():

cout << "time remaining: " << setfill('0')
     << setw(2) <<  hr << ':' << setw(2) << mins << ':' << setw(2) << secs;

If you want a std::string as result, you can use a std::ostringstream in the same manner:

std::ostringstream oss;
oss << setfill('0')
     << setw(2) <<  hr << ':' << setw(2) << mins << ':' << setw(2) << secs;
cout << "time remaining: " << oss.str();

Also there's a boost library boost::format available, that resembles the format string/place holder syntax.

0
On

You can do it with C++20 std::format (godbolt):

std::string s = std::format("time remaining: {:02}::{:02}::{:02}",
                            hr, mins, secs);

On older systems you can use the {fmt} library, std::format is based on.

Disclaimer: I'm the author of {fmt} and C++20 std::format.