c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒。
#include <iostream>
#include <string>
#include <iomanip> // 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.