请用C++写一份读取文本信息与现行时间进行判断 是否到期不使用get_time
以下是使用C++编写的读取文本信息并与当前时间进行判断是否到期的示例代码:
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>
bool isExpired(const std::string& dateStr) {
std::tm date = {};
std::istringstream iss(dateStr);
iss >> std::get_time(&date, "%Y-%m-%d");
if (iss.fail()) {
std::cerr << "Invalid date format: " << dateStr << std::endl;
return false;
}
std::time_t now = std::time(nullptr);
std::tm* currentTime = std::localtime(&now);
return std::mktime(currentTime) > std::mktime(&date);
}
int main() {
std::string filePath = "expiry_date.txt";
std::ifstream file(filePath);
if (!file.is_open()) {
std::cerr << "Failed to open file: " << filePath << std::endl;
return 1;
}
std::string expiryDate;
file >> expiryDate;
if (isExpired(expiryDate)) {
std::cout << "The product has expired." << std::endl;
} else {
std::cout << "The product is still valid." << std::endl;
}
file.close();
return 0;
}
假设文本文件 expiry_date.txt 中只包含一个日期,格式为 YYYY-MM-DD,表示产品的到期日期。程序会读取该日期并与当前时间进行比较,判断产品是否已经过期。如果过期,则输出相应信息;否则,输出产品仍然有效的信息
原文地址: https://www.cveoy.top/t/topic/hUuO 著作权归作者所有。请勿转载和采集!