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::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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值