如何打印一堆具有相同格式的整数?

Ali*_*Ali 4 c++ code-duplication iomanip c++11

我想在 2 个字段上打印一堆整数作为'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;
}
Run Code Online (Sandbox Code Playgroud)

我努力了

std::ostream& operator<<(std::ostream& s, int i) {

    return s << std::setw(2) << std::setfill('0') << i;
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用,operator<<调用是不明确的。


编辑我得到了 4 个很棒的答案,我选择了可​​能是最简单和最通用的一个(也就是说,不假设我们正在处理时间戳)。对于实际问题,我可能会使用std::put_timeorthough strftime

vit*_*aut 5

在 C++20 中,您将能够std::format以更简洁的方式执行此操作:

    ss << std::format("{}{:02}{:02}{:02}{:02}{:02}",
                      t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
                      t.tm_hour, t.tm_min, t.tm_sec);
Run Code Online (Sandbox Code Playgroud)

使用支持直接格式化的{fmt} 库甚至更容易:tm

auto s = fmt::format("{:%Y%m%d%H%M%S}", t);
Run Code Online (Sandbox Code Playgroud)