我需要获取两位数格式的日期和月份。但是,不是一直使用 setw,而是有一个设置可以说将每个字段设置为最小“x”长度。
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();
}
最佳答案
Iostream 是变化无常的,您不能真正依赖各种格式化标志来保持。但是,您可以使用 <iomanip>
把事情写得更简洁一点:
#include <iomanip>
using namespace std;
o << setw(2) << setfill('0') << x;
像 o << hex
这样的修饰符和 o << uppercase
通常持续存在,而精度和字段宽度修饰符则不会。不确定填充字符。
关于c++ - 有没有办法一次性设置每个字段的宽度,而不是每次都使用 streamio 设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6796808/