如今,您可能应该将计时持续时间std::chrono::milliseconds用于此类任务,但如果您想使我们自己的类型支持格式设置,则应执行以下操作:
#include <iomanip> // std::setw & std::setfill
#include <iostream>
// your own type
struct seconds_t {
double value;
};
// ostream operator for your type:
std::ostream& operator<<(std::ostream& os,const seconds_t& v) {
// convert to milliseconds
int ms = static_cast<int>(v.value * 1000.);
int h = ms / (1000 * 60 * 60);
ms -= h * (1000 * 60 * 60);
int m = ms / (1000 * 60);
ms -= m * (1000 * 60);
int s = ms / 1000;
ms -= s * 1000;
return os << std::setfill('0') << std::setw(2) << h << ':' << std::setw(2) << m
<< ':' << std::setw(2) << s << '.' << std::setw(3) << ms;
}
int main() {
seconds_t m{3907.1};
std::cout << m << "\n";
}
,
C ++ 20中的新功能
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int
main()
{
double sec_tot = 3907.1;
cout << format("{:%T}\n",round<milliseconds>(duration<double>{sec_tot}));
}
,
printf
样式格式说明符不起作用。您将需要使用流操纵器来设置width和fill character。
ss << std:setw(2) << std::setfill('0') << hour_int;
,
这还将添加一个前导零以强制使用hh:mm:ss格式。
如果hh为00,则仅返回mm:ss。
此示例中省略了ms,但易于添加。
#include <iostream>
std::string convertSecondsToHHMMSS (int value) {
std::string result;
// compute h,m,s
std::string h = std::to_string(value / 3600);
std::string m = std::to_string((value % 3600) / 60);
std::string s = std::to_string(value % 60);
// add leading zero if needed
std::string hh = std::string(2 - h.length(),'0') + h;
std::string mm = std::string(2 - m.length(),'0') + m;
std::string ss = std::string(2 - s.length(),'0') + s;
// return mm:ss if hh is 00
if (hh.compare("00") != 0) {
result = hh + ':' + mm + ":" + ss;
}
else {
result = mm + ":" + ss;
}
return result;
}
int main() {
std::cout << convertSecondsToHHMMSS(3601) << "\n";
std::cout << convertSecondsToHHMMSS(1111) << "\n";
std::cout << convertSecondsToHHMMSS(60) << "\n";
std::cout << convertSecondsToHHMMSS(12) << "\n";
std::cout << convertSecondsToHHMMSS(0) << "\n";
}
本文链接:https://www.f2er.com/3165833.html