我需要将秒转换为hh:mm:ss.milliseconds,并且我需要这种格式必须得到尊重。我的意思是小时,分钟和秒必须有2位数字,毫秒必须有3位数字。
例如,如果秒= 3907.1,我将获得01:05:07.100

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sstream>
#include <math.h>
using namespace std;

int main()
{
    double sec_tot = 3907.1;
    double hour = sec_tot/3600; // seconds in hours
    double hour_int;
    double hour_fra = modf(hour, &hour_int );//split integer and decimal part of hours
    double minutes = hour_fra*60; // dacimal hours in minutes
    double minutes_int;
    double minutes_fra = modf(minutes, &minutes_int); // split integer and decimal part of minutes
    double seconds = minutes_fra*60; // decimal minutes in seconds
    stringstream ss;
    ss << ("%02lf", hour_int) << ":" << ("%02lf", minutes_int) << ":" << ("%02lf", seconds);
    string time_obs_def = ss.str();
    cout << time_obs_def << endl;

    return 0;
}

但输出为1:5:7.1
谢谢。

最佳答案

如今,您可能应该将计时持续时间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++ - 如何将秒转换为hh:mm:ss.millisecond格式C++?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58695875/

10-09 07:13
查看更多