用c++写一个程序,将24小时时间格式转化为12小时时间格式。定义一个time mistake的异常类,处理用户输入的非法时间,比如10:65或者无效字符
时间: 2024-02-18 09:02:54 浏览: 42
好的,我可以帮你写一个C++程序来实现这个功能,并且处理用户输入的非法时间。下面是代码,希望能够帮到你:
```cpp
#include <iostream>
#include <string>
#include <regex>
using namespace std;
class time_mistake : public exception {
public:
const char* what() const throw() {
return "非法时间格式!";
}
};
string convertTimeFormat(string time) {
regex pattern("([0-9]{2}):([0-9]{2})");
smatch match;
regex_search(time, match, pattern);
int hour = stoi(match[1]);
int minute = stoi(match[2]);
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
throw time_mistake();
}
string suffix = hour < 12 ? "AM" : "PM";
hour = hour % 12;
if (hour == 0) {
hour = 12;
}
return to_string(hour) + ":" + match[2] + " " + suffix;
}
int main() {
string time;
cout << "请输入24小时时间格式(如:13:30):" << endl;
cin >> time;
try {
string result = convertTimeFormat(time);
cout << "12小时时间格式为:" << result << endl;
}
catch (time_mistake& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
```
程序中定义了一个`time_mistake`异常类,用来处理用户输入的非法时间。在`convertTimeFormat`函数中,使用正则表达式提取输入字符串中的小时和分钟,并进行格式转换。如果输入时间不符合规范,将抛出`time_mistake`异常。在`main`函数中,捕获异常并输出错误信息,或者输出转换后的时间格式。
希望这个程序能够满足你的需求,如果还有其他问题,请随时提出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)