c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒
创始人
2024-11-15 09:37:38

c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒。

#include  #include  #include  // For std::setw and std::setfill  std::string convertSecondsToTimeString(int seconds) {    if (seconds > 86400) { // Check if seconds exceed 24 hours     return "Error: Input exceeds maximum of 24 hours.";   }      int hours = seconds / 3600; // Calculate the hours   seconds %= 3600; // Remaining seconds after removing full hours   int minutes = seconds / 60; // Calculate the minutes   seconds %= 60; // Remaining seconds    // Create an ostringstream to format the output   std::ostringstream timeStream;   // Set the width to 2 for each part and fill with '0' if needed   timeStream << std::setw(2) << std::setfill('0') << hours << ":"     << std::setw(2) << std::setfill('0') << minutes << ":"     << std::setw(2) << std::setfill('0') << seconds;    return timeStream.str(); }  int main() {   int seconds = 2991; // Example input   std::string timeString = convertSecondsToTimeString(seconds);   std::cout << "Time in hh:mm:ss format: " << timeString << std::endl;    int seconds1 = 11126991; // Example input   std::string timeString1 = convertSecondsToTimeString(seconds1);   std::cout << "Time in hh:mm:ss format: " << timeString1 << std::endl;   return 0; } 

输出结果:

Time in hh:mm:ss format: 00:49:51 Time in hh:mm:ss format: Error: Input exceeds maximum of 24 hours. 

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...