C++输入包括两行,两行均为一个“时:分:秒”格式的时间,输出就是输入的两个时间之间的秒数差
时间: 2024-10-20 20:18:11 浏览: 28
在C++中,你可以使用`std::chrono`库来处理时间和计算时间间隔。下面是一个简单的示例程序,它接收两个时间字符串,按照“时:分:秒”的格式,然后计算它们之间的秒数差:
```cpp
#include <iostream>
#include <chrono>
#include <string>
#include <sstream>
struct TimeParser {
std::chrono::hours hours;
std::chrono::minutes minutes;
std::chrono::seconds seconds;
void parse(const std::string& time_str) {
std::istringstream iss(time_str);
char delimiter;
iss >> hours >> delimiter >> minutes >> delimiter >> seconds;
if (iss.fail()) throw std::invalid_argument("Invalid time format");
}
std::chrono::seconds to_seconds() const {
return std::chrono::duration_cast<std::chrono::seconds>(hours.count() * 3600 +
minutes.count() * 60 +
seconds.count());
}
};
int main() {
std::string time1, time2;
std::cout << "请输入第一个时间(时:分:秒格式):" << std::endl;
std::getline(std::cin, time1);
TimeParser parser1;
try {
parser1.parse(time1);
} catch (const std::invalid_argument& e) {
std::cerr << "错误: " << e.what() << ". 请重新输入有效时间。\n";
return 1;
}
std::cout << "请输入第二个时间:" << std::endl;
std::getline(std::cin, time2);
TimeParser parser2;
try {
parser2.parse(time2);
} catch (const std::invalid_argument& e) {
std::cerr << "错误: " << e.what() << ". 请重新输入有效时间。\n";
return 1;
}
auto diff_seconds = parser2.to_seconds() - parser1.to_seconds();
std::cout << "两个时间之间的秒数差: " << diff_seconds.count() << "秒\n";
return 0;
}
```
这个程序首先定义了一个`TimeParser`类,用于解析输入的时间字符串。然后在主函数中,分别从用户那里获取两个时间字符串,并通过`parse`方法将其转换为`std::chrono::seconds`。最后,计算两者之间的时间差并打印结果。
阅读全文
相关推荐

















