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();
}
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:Modifiers like
o << hexando << uppercaseusually persist, while precision and field width modifiers don’t. Not sure about the fill character.