是否存在计算24小时制时间的函数?用于长途通话计费场景
12小时制转24小时制的C++实现方案
当然有办法搞定这个转换需求啦!C++标准库虽然没有直接的“一键转换”函数,但我们可以通过两种实用的方式来实现,刚好能适配你开发长途通话计费功能的场景:
方案一:利用标准库的时间解析与格式化函数
你可以借助<ctime>头文件里的strptime和strftime函数来完成转换,这两个函数能帮你轻松解析12小时制时间,再输出成24小时制格式。
给你整合到现有代码里的示例:
#include <iostream> #include <string> #include <ctime> // 引入时间处理头文件 using namespace std; int main() { char day, day2; string inputTime; struct tm timeStruct = {0}; // 初始化时间结构体 cout << "Please enter the first two letters of the day you have made the call:\n"; cin >> day >> day2; cout << "Please enter the time you have made the call (e.g., 1:30 PM):\n"; cin >> inputTime; // 解析12小时制时间到结构体 strptime(inputTime.c_str(), "%I:%M %p", &timeStruct); // 格式化为24小时制字符串 char outputTime[20]; strftime(outputTime, sizeof(outputTime), "%H:%M", &timeStruct); cout << "Converted 24-hour time: " << outputTime << endl; // 这里可以继续你的计费逻辑... int hours = timeStruct.tm_hour; int minutes = timeStruct.tm_min; // 后续计算cost的代码... return 0; }
说明:%I对应12小时制的小时,%p对应AM/PM标识,%H对应24小时制的小时,%M是分钟。
方案二:手动实现转换函数(更灵活可控)
如果不需要依赖标准库的时间结构体,你也可以自己写一个转换函数,直接处理输入的时间字符串,逻辑更直观:
#include <iostream> #include <string> #include <sstream> using namespace std; // 自定义转换函数:输入12小时制时间(带AM/PM),返回24小时制的小时和分钟 void convertTo24Hour(const string& timeStr, int& hour, int& minute) { string period; char colon; istringstream iss(timeStr); iss >> hour >> colon >> minute >> period; if (period == "PM" && hour != 12) { hour += 12; } else if (period == "AM" && hour == 12) { hour = 0; } } int main() { char day, day2; string inputTime; int hour24, minute24; cout << "Please enter the first two letters of the day you have made the call:\n"; cin >> day >> day2; cout << "Please enter the time you have made the call (e.g., 1:30 PM):\n"; cin >> inputTime; convertTo24Hour(inputTime, hour24, minute24); cout << "Converted 24-hour time: " << hour24 << ":" << minute24 << endl; // 继续你的计费逻辑... double cost; // 根据hour24等计算费用... return 0; }
这个方案适合你需要直接获取小时和分钟数值来计算计费的场景,不用额外处理时间结构体。如果你的输入是中文的“上午/下午”,只需要把函数里的period判断改成对应的中文就行,比如判断period == "下午"或者period == "上午"。
内容的提问来源于stack exchange,提问作者Fatma Ashraf
相关产品推荐
相关产品推荐

