VS使用C++20打印std::chrono::time_point时抛出错误求助
解决std::chrono::time_point无法直接输出到cout的错误
C++标准库默认没有为std::chrono::time_point类型重载operator<<,所以直接执行cout << currTime会触发"no operator found which takes a right hand operand of type std::chrono::time_point"错误。以下是几种可行的解决方法:
方法1:转换为std::time_t后格式化输出
将time_point转换为C风格的time_t类型,再通过时间格式化函数输出:
#include <chrono> #include <iostream> #include <ctime> int main() { std::chrono::time_point currTime = std::chrono::system_clock::now(); // 转换为time_t类型 std::time_t currTimeT = std::chrono::system_clock::to_time_t(currTime); // 直接输出本地时间字符串(自带换行) std::cout << std::ctime(&currTimeT); // 自定义格式输出(更灵活) char timeBuffer[80]; std::tm* localTime = std::localtime(&currTimeT); std::strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", localTime); std::cout << timeBuffer << std::endl; return 0; }
方法2:利用C++20的std::format原生支持
既然你使用的是C++20标准,可以直接用std::format来格式化输出time_point,无需额外转换:
#include <chrono> #include <iostream> #include <format> int main() { auto currTime = std::chrono::system_clock::now(); // 自定义时间格式输出 std::cout << std::format("{:%Y-%m-%d %H:%M:%S}", currTime) << std::endl; return 0; }
std::format支持丰富的时间格式占位符,可根据需求调整格式字符串。
方法3:输出时间点的纪元时长
如果只需要输出从纪元开始的时长(比如毫秒、秒数),可以直接转换为对应时长类型后输出:
#include <chrono> #include <iostream> int main() { auto currTime = std::chrono::system_clock::now(); // 转换为毫秒数输出 auto msSinceEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(currTime.time_since_epoch()); std::cout << msSinceEpoch.count() << " ms since epoch" << std::endl; return 0; }
内容的提问来源于stack exchange,提问作者lorem1213
相关产品推荐
相关产品推荐

