欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒

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

2025/2/24 21:15:10 来源:https://blog.csdn.net/weixin_48617416/article/details/140754693  浏览:    关键词:c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒

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

#include <iostream>
#include <string>
#include <iomanip> // For std::setw and std::setfillstd::string convertSecondsToTimeString(int seconds) {if (seconds > 86400) { // Check if seconds exceed 24 hoursreturn "Error: Input exceeds maximum of 24 hours.";}int hours = seconds / 3600; // Calculate the hoursseconds %= 3600; // Remaining seconds after removing full hoursint minutes = seconds / 60; // Calculate the minutesseconds %= 60; // Remaining seconds// Create an ostringstream to format the outputstd::ostringstream timeStream;// Set the width to 2 for each part and fill with '0' if neededtimeStream << 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 inputstd::string timeString = convertSecondsToTimeString(seconds);std::cout << "Time in hh:mm:ss format: " << timeString << std::endl;int seconds1 = 11126991; // Example inputstd::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.

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词