gpt4 book ai didi

c++ - 有没有办法一次性设置每个字段的宽度,而不是每次都使用 streamio 设置?

转载 作者:行者123 更新时间:2023-11-27 23:29:16 25 4
gpt4 key购买 nike

我需要获取两位数格式的日期和月份。但是,不是一直使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com