How can I Format Width in puttime?

主宰稳场 提交于 2019-12-12 04:31:05

问题


Let's say that 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'd like to accomplish this like:

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 puttime doesn't seem to allow me to use field flags in it's format fields. Additionally this puttime doesn't seem to play nice with setw.

Is my only option to do strftime and then use that with setw?


回答1:


Here is a header-only library that respects the 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 this out yourself by pasting the above code into this 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



回答2:


The following will also work

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;
    }


来源:https://stackoverflow.com/questions/40132424/how-can-i-format-width-in-puttime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!