How can I format the width in puttime?

Say I want to print something simple, like this table:

January   1
February  2
March     3
April     4
May       5
June      6
July      7
August    8
September 9
October   10
November  11
December  12

I would like to do the following:

for(tm i{ 0, 0, 0, 1, 0 }; i.tm_mon < 12; ++i.tm_mon) cout << put_time(&i, "%-9B") << i.tm_mon + 1 << endl;

Unfortunately, puttimeit does not seem to allow me to use field flags in format fields. Also, this puttimeone doesn't seem to play well with setw.

Am I the only option to do strftimeand then use it with setw?

0
source share
2 answers

Here is a header-only library that deals with I / O manipulators:

#include "date.h"
#include <iomanip>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    auto m = jan;
    do
    {
        cout << left << setw(10) << format("%B", sys_days{m/1/1}) << right
             << unsigned(m) << '\n';
    } while (++m != jan);
}

You can try it yourself by pasting the above code into the wandbox link .

January   1
February  2
March     3
April     4
May       5
June      6
July      7
August    8
September 9
October   10
November  11
December  12
+1
source

for(tm i{ 0, 0, 0, 1, 0 }; i.tm_mon < 12; ++i.tm_mon)
    {
        std::stringstream oss;
        oss << std::put_time(&i, "%B");
        string str = oss.str();
        cout << std::setiosflags(std::ios::left) << setw( 10 )  << str << setw( 2 ) << i.tm_mon + 1 << endl;
    }
+1

All Articles