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.