【发布时间】:2020-11-17 21:56:29
【问题描述】:
有这个课程:
date.hpp:
#ifndef DATE_HPP
#define DATE_HPP
#include <time.h>
#include <iostream>
#include <sstream>
class Date
{
std::stringstream format;
time_t date;
struct tm *date_tm;
public:
Date() : date(time(NULL)), date_tm(localtime(&date)) {}
Date(std::istream &in);
Date(std::string str);
const std::string getDate();
const bool dateMatch(std::string str);
};
#endif //DATE_HPP
还有这个演员:date.cpp:
#include "date.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <regex>
bool isDate(std::string target)
{
std::regex reg("[1-12]{2}/[1-31]{2}[00-99]{2}");
return std::regex_search(target, reg);
}
Date::Date(std::istream &in)
{
date_tm = new struct tm;
std::cout << "enter date [mm/dd/yy]: ";
format.basic_ios::rdbuf(in.rdbuf());
if (isDate(format.str()))
{
format >> std::get_time(date_tm, "%m/%d/%y");
}
else
{
std::cout << "Format of date is not valid\n";
}
}
...
如果我尝试使用带有std::istream 参数的ctor:
#include "date.hpp"
#include <iostream>
using namespace std;
int main()
{
Date d(cin);
cout << d.getDate() << '\n';
}
然后,日期格式检查甚至在我可以写入 cin 之前就失败了。现在怎么了?
【问题讨论】:
-
哦,男孩,请不要在这样的构造函数中写信给
cout。如果您需要像文件流一样从cin以外的流中实例化Date怎么办? -
那么我应该如何警告用户日期格式错误?
-
我的意思主要是提示
std::cout << "enter date [mm/dd/yy]: ";。错误条件可以通过异常或状态代码来表示。调用代码可以决定在这种情况下要做什么,比如写一条错误消息。 -
好的,谢谢,我会编辑的。