nsivakr
nsivakr

Reputation: 1595

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 sCurDateTime(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();

}

Upvotes: 0

Views: 1484

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308392

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

Upvotes: 0

Roland Illig
Roland Illig

Reputation: 41676

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.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477358

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.

Upvotes: 4

Related Questions