'Printing the time in milliseconds in c++

HI I'm trying to log a sensor data to CSV file. I want the first row to be hh:mm:ss:ms.

The Code I have is

    #include <chrono>
#include <ctime>
eyeDataLog << std::ctime(&today_time) << ","
<< gazeleft[0] << ","
<< gazeleft[1] << "," 

|Timestamp2 |left gaze X |left gaze Y |left gaze Z |right gaze X

|Tue Mar 1 18:19:31 2022 |0 |0 |0 |0

how to add milliseconds to the logged time regared thanks



Solution 1:[1]

You may try strftime or other library like fmt which is included in c++20.

Update: even you don't use C++20, fmt library itself is compatible with c++11 and above.

Since you have formatting requirement in logging, fmt might fit well.

Demo for fmt

#include <fmt/chrono.h>

int main() {
  using namespace std::literals::chrono_literals;
  fmt::print("Default format: {} {}\n", 42s, 100ms);
  // %S prints milliseconds
  fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s + 15ms);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1