作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要获取两位数格式的日期和月份。但是,不是一直使用 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/
我是一名优秀的程序员,十分优秀!