是否有一种方法可以在一次拍摄中设置每个字段的宽度,而不是每次使用流媒体设置
Is there a way to set the width of each field at one shot instead of setting every time using streamio?
我需要以两位数格式获得日期和月份。但是不是一直使用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 << hex
和o << 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) ;
相关文章:
- 有没有办法在链接时设置精灵需要字段?
- 如何将必需的 protobuf 字段设置为其默认值?
- 无法从JNI设置Java Int数组字段
- 在模板专业化期间,如何设置C 结构中的静态字段
- 使用反射在 protobuf 中设置重复字段
- 在C 中以通用方式构建对象,设置字段并返回对象
- 使用父类构造函数初始化列表中的嵌套类字段中设置值
- C++使用成员字段设置比较器
- 构造函数将数组字段设置为 null
- 谷歌协议缓冲区,如何设置自定义类型的字段
- 如何在 CORBA 中获取和设置类字段?(处理 CORBA 对象的序列)
- 是否设置数组的某些字段,将其他字段设置为零
- 如何在 protobuf 中使用反射将预分配的消息设置为字段C++
- 如何使用模板设置联合的字段
- 如何通过派生类的方法复制来设置基类字段
- 在 C 中使用占位符设置字段宽度,并'char'
- 在谷歌协议缓冲区中设置重复字段时出错
- C++联合字段未正确设置
- 在C++中将默认参数设置为nullptr和非静态类字段
- CDHtmlDialog将焦点设置在输入字段上