开发者

Is there a way to set the width of each field at one shot instead of setting every time using streamio?

I need to get the date and month in two digit format. But instead of using setw all the time, is there a single setting to say that set every field to minimum 'x' length.

void getDate(std::string& m_resultDate)
{

    time_t curTime;
    struct tm *curTimeInfo;
    std::stringstream sCurDa开发者_开发技巧teTime(std::stringstream::out | std::stringstream::in);

    time(&curTime);
    curTimeInfo = localtime(&curTime);

    sCurDateTime.width(4);
    sCurDateTime.fill('0');

    sCurDateTime << ( curTimeInfo->tm_year + 1900 );
    sCurDateTime.width(2);
    sCurDateTime.fill('0');

    sCurDateTime << ( curTimeInfo->tm_mon) ;

    sCurDateTime.width(2);
    sCurDateTime.fill('0');
    sCurDateTime << ( curTimeInfo->tm_mday) ;

    m_resultDate = sCurDateTime.str();

}


Iostreams are fickle, and you cannot really rely on the various formatting flags to persist. However, you can use <iomanip> to write things a bit more concisely:

#include <iomanip>
using namespace std;
o << setw(2) << setfill('0') << x;

Modifiers like o << hex and o << uppercase usually persist, while precision and field width modifiers don't. Not sure about the fill character.


It seems to me that the C++ streams are not really suited to formatting things. Compare with this simple code:

#include <cstring>

char buf[9];
std::snprintf(buf, sizeof buf, "%04d%02d%02d",
    curTimeInfo->tm_year + 1900, 
    curTimeInfo->tm_mon + 1, // note the +1 here
    curTimeInfo->tm_mday);

Maybe it's not the real complicated C++ style, but it's clear and concise.


Any time you find yourself doing something over and over again, you should wrap it in a function. It's an application of the DRY principle.

void OutputFormattedInteger(std::stringstream & stream, int value, int width)
{
    stream.width(width);
    stream.fill('0');
    stream << value;
}

OutputFormattedInteger( sCurDateTime, curTimeInfo->tm_year + 1900, 4 );
OutputFormattedInteger( sCurDateTime, curTimeInfo->tm_mon, 2) ;
OutputFormattedInteger( sCurDateTime, curTimeInfo->tm_mday, 2) ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜