【发布时间】:2012-12-29 18:37:51
【问题描述】:
我想在两个字段上打印一堆整数,'0' 作为填充字符。我可以做到,但这会导致代码重复。我应该如何更改代码以便排除重复代码?
#include <ctime>
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
string timestamp() {
time_t now = time(0);
tm t = *localtime(&now);
ostringstream ss;
t.tm_mday = 9; // cheat a little to test it
t.tm_hour = 8;
ss << (t.tm_year+1900)
<< setw(2) << setfill('0') << (t.tm_mon+1) // Code duplication
<< setw(2) << setfill('0') << t.tm_mday
<< setw(2) << setfill('0') << t.tm_hour
<< setw(2) << setfill('0') << t.tm_min
<< setw(2) << setfill('0') << t.tm_sec;
return ss.str();
}
int main() {
cout << timestamp() << endl;
return 0;
}
我试过了
std::ostream& operator<<(std::ostream& s, int i) {
return s << std::setw(2) << std::setfill('0') << i;
}
但它不起作用,operator<< 调用是模棱两可的。
编辑我得到了 4 个很棒的答案,我选择了一个可能是最简单和最通用的答案(也就是说,不假设我们正在处理时间戳)。对于实际问题,我可能会使用std::put_time 或strftime。
【问题讨论】:
-
为
int创建一个新的ostream& operator<<是一个非常糟糕的主意。 :) -
@LightnessRacesinOrbit 是的,我也想通了。有什么建议可以代替吗?
-
如果您尝试格式化日期/时间,您可能需要查看:en.cppreference.com/w/cpp/io/manip/put_time
-
@zahir Awesome:你能把它作为答案发布吗?我想投赞成票!
标签: c++ c++11 code-duplication iomanip