是否有一种方法可以在一次拍摄中设置每个字段的宽度,而不是每次使用流媒体设置

Is there a way to set the width of each field at one shot instead of setting every time using streamio?

本文关键字:设置 字段 流媒体 方法 一种 是否 一次      更新时间:2023-10-16

我需要以两位数格式获得日期和月份。但是不是一直使用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();
}

Iostreams是多变的,您不能真正依赖于各种格式化标志来持久。但是,您可以使用<iomanip>将内容写得更简洁一些:

#include <iomanip>
using namespace std;
o << setw(2) << setfill('0') << x;
o << hexo << uppercase这样的

修饰符通常会保留,而精度和字段宽度修饰符则不会。不确定填充字符

在我看来,c++流并不真正适合格式化事物。对比下面的简单代码:

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

也许这不是真正复杂的c++风格,但它清晰而简洁。

任何时候你发现自己在反复地做某件事,你应该把它包装在一个函数中。这是DRY原则的一个应用。

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