3

ミリ秒の精度でa を出力するための簡潔なソリューションを探していboost::posix_time::time_durationます。正確に 3 桁の小数秒が必要です。デフォルトのフォーマットでは、6 桁の小数桁が生成されます (または、すべて 0 の場合は何も生成されません)。

#include <boost/date_time.hpp>
#include <iostream>

int main()
{
    // Define some duration in milliseconds:
    int64_t start_msecs((((40 * 60) + 3) * 60 + 2) * 1000 + 1);

    // The same as time_duration:
    boost::posix_time::time_duration start_time =
        boost::posix_time::milliseconds(start_msecs);

    // No suitable format (for MP4Box chapter starts): ////////////////////
    std::cout << "Wrong format: "
        << std::setprecision(3) // <-- No effect!?
        << start_time << std::endl;
    // Output: "Wrong format: 40:03:02.001000"
    // Required format      : 40:03:02.001

    return 0;
}

ファセットといくつかの回避策を使用して、必要な出力を得ることができます。しかし、そのソリューションは、必要に応じて構成できない日時ライブラリの部分のみを無効にし、それらを低レベルの実装に置き換えます。

#include <boost/date_time.hpp>
#include <iostream>

int main()
{
    // Define some duration in milliseconds:
    int64_t start_msecs((((40 * 60) + 3) * 60 + 2) * 1000 + 1);

    // The same as time_duration:
    boost::posix_time::time_duration start_time =
            boost::posix_time::milliseconds(start_msecs);

    // Define output format without fractional seconds:
    boost::posix_time::time_facet *output_facet =
        new boost::posix_time::time_facet();
    output_facet->time_duration_format("%O:%M:%S");

    // Imbue cout with format for duration output:
    std::cout.imbue(std::locale(std::locale::classic(), output_facet));

    // Only the milliseconds:
    int64_t msecs_only = start_msecs % 1000;

    // Render duration with exactly 3 fractional-second digits: ///////////
    std::cout << "Working: "
        << start_time << "."
        << std::setw(3) << std::right << std::setfill('0')
        << msecs_only << std::endl;
    // Output: "Working: 40:03:02.001"

    return 0;
}

必要な出力を達成するための推奨される方法は何ですか?

4

0 に答える 0