如何让重载的C++ std::cout输出运算符获取当前std::setprecision设置?
读取std::ostream的setprecision值适配time_t*输出格式
要读取当前std::ostream的setprecision设置,直接调用流对象的precision()成员函数即可,它会返回当前的精度值。基于这个值,你可以在重载的operator<<里分支处理不同的输出格式。
修改后的重载函数代码
namespace std { std::ostream& operator<< (std::ostream& out, const time_t* _rawtime) { struct tm timeinfo{}; #ifdef WIN32 localtime_s(&timeinfo, _rawtime); #else // 用localtime_r替代localtime,避免线程安全问题 localtime_r(_rawtime, &timeinfo); #endif int current_precision = out.precision(); if (current_precision <= 4) { // 精度<=4,仅输出年份 out << (timeinfo.tm_year + 1900); } else if (current_precision <= 7) { // 精度4<x<=7,输出年-月 out << (timeinfo.tm_year + 1900) << "-" << (timeinfo.tm_mon + 1); } else { // 精度>7,输出完整年月日 out << (timeinfo.tm_year + 1900) << "-" << (timeinfo.tm_mon + 1) << "-" << timeinfo.tm_mday; } return out; } }
关键说明
- 获取精度值:
out.precision()直接返回当前流的精度设置,无需额外操作。 - 分支逻辑:根据你的需求划分精度区间,对应不同的日期格式输出。
- 线程安全优化:非Windows平台下,用
localtime_r替代localtime,避免localtime返回的静态缓冲区被多线程篡改的问题。
测试代码验证
#include <iostream> #include <iomanip> #include <ctime> int main() { time_t dummy = 123456789; std::cout << std::setprecision(4) << &dummy << std::endl; // 输出1973 std::cout << std::setprecision(7) << &dummy << std::endl; // 输出1973-11 std::cout << std::setprecision(10) << &dummy << std::endl; // 输出1973-11-30 return 0; }
内容的提问来源于stack exchange,提问作者Bruce
相关产品推荐
相关产品推荐

