利用c++写一个程序,将24小时格式时间转换为12小时格式。定义一个名为TimeMistake的异常类,处理用户输入的非法时间,比如10:65或者无效字符
时间: 2024-02-28 19:57:09 浏览: 33
好的,以下是一个 C++ 实现的程序,可以将24小时格式的时间转换为12小时格式,并处理用户输入的非法时间:
```c++
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace std;
class TimeMistake : public exception {
public:
TimeMistake(const string& msg) : message(msg) {}
const char* what() const noexcept override {
return message.c_str();
}
private:
string message;
};
string convert_time(const string& time_str) {
try {
stringstream ss(time_str);
int hour, minute;
char colon;
ss >> hour >> colon >> minute;
if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || colon != ':') {
throw TimeMistake("Invalid time: " + time_str);
}
stringstream result;
if (hour == 0) {
result << "12:" << setfill('0') << setw(2) << minute << " AM";
} else if (hour < 12) {
result << hour << ":" << setfill('0') << setw(2) << minute << " AM";
} else if (hour == 12) {
result << "12:" << setfill('0') << setw(2) << minute << " PM";
} else {
result << hour - 12 << ":" << setfill('0') << setw(2) << minute << " PM";
}
return result.str();
} catch (const exception& e) {
throw TimeMistake("Invalid time format: " + time_str);
}
}
int main() {
while (true) {
try {
string time_str;
cout << "Please enter a time in 24-hour format (e.g. 14:30): ";
getline(cin, time_str);
cout << convert_time(time_str) << endl;
} catch (const TimeMistake& e) {
cerr << "Error: " << e.what() << endl;
}
}
return 0;
}
```
程序中定义了一个名为 `TimeMistake` 的异常类,用于处理用户输入的非法时间。在 `convert_time` 函数中,程序首先尝试将输入的时间字符串按照冒号分隔,解析出小时和分钟。如果解析失败或者小时或分钟不在合法范围内,或者冒号的数量不正确,则抛出 `TimeMistake` 异常。否则,程序根据小时数和分钟数计算出12小时格式的时间,并将其作为字符串返回。
在程序的主函数中,程序反复询问用户输入,调用 `convert_time` 函数进行转换,并处理可能抛出的 `TimeMistake` 异常。