构建正则表达式时不会发生您的异常,但是当您抛出自己的异常时。
首先你要检查你的字符串正好是10个字符长。 如果你把尺寸10一串字符串中的一切工作,因为它应该:
int main()
{
std::string str = "20151107AB";
int year = 0;
int month = 0;
int day= 0;
if (str.size() != 10)
throw std::exception("not a date");
std::regex regEx("^[0-9]{4}[0-9]{2}[0-9]{2}");
std::regex delims("([^.,;-]+)");
std::smatch match;
if (std::regex_match(str.cbegin(), str.cend(), match, regEx)) {
std::stringstream ss;
std::string tmp(match.str());
std::copy(std::sregex_token_iterator(tmp.cbegin(), tmp.cend(), delims, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(ss, "\n"));
ss >> year;
ss >> month;
ss >> day;
}
}
如果删除了“AB”作为您的问题描述,你会得到错误。
int main()
{
std::string str = "20151107";
int year = 0;
int month = 0;
int day= 0;
if (str.size() != 10)
throw std::exception("not a date");
std::regex regEx("^[0-9]{4}[0-9]{2}[0-9]{2}");
std::regex delims("([^.,;-]+)");
std::smatch match;
if (std::regex_match(str.cbegin(), str.cend(), match, regEx)) {
std::stringstream ss;
std::string tmp(match.str());
std::copy(std::sregex_token_iterator(tmp.cbegin(), tmp.cend(), delims, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(ss, "\n"));
ss >> year;
ss >> month;
ss >> day;
}
}
如果您现在删除长度检查一切正常,因为它应该再次。
int main()
{
std::string str = "20151107";
int year = 0;
int month = 0;
int day= 0;
std::regex regEx("^[0-9]{4}[0-9]{2}[0-9]{2}");
std::regex delims("([^.,;-]+)");
std::smatch match;
if (std::regex_match(str.cbegin(), str.cend(), match, regEx)) {
std::stringstream ss;
std::string tmp(match.str());
std::copy(std::sregex_token_iterator(tmp.cbegin(), tmp.cend(), delims, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(ss, "\n"));
ss >> year;
ss >> month;
ss >> day;
}
}
另外,如果赶上例外一切仍是罚款(但不执行代码)
int main()
{
try
{
std::string str = "20151107";
int year = 0;
int month = 0;
int day = 0;
if (str.size() != 10)
throw std::exception("not a date");
std::regex regEx("^[0-9]{4}[0-9]{2}[0-9]{2}");
std::regex delims("([^.,;-]+)");
std::smatch match;
if (std::regex_match(str.cbegin(), str.cend(), match, regEx)) {
std::stringstream ss;
std::string tmp(match.str());
std::copy(std::sregex_token_iterator(tmp.cbegin(), tmp.cend(), delims, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(ss, "\n"));
ss >> year;
ss >> month;
ss >> day;
}
}
catch (std::exception& e)
{
//handle
}
}
所以我对这个假设是,你不捕获异常的任何地方,这可能导致内存损坏,因为标准没有定义在这种情况下堆栈是否必须展开。
我会推荐给 1.阅读Does it make sense to catch exceptions in the main(...)? 2.正确捕获由Date::operator=
抛出的异常也许你还需要安装一个全球性的异常处理程序(安全地关闭您的程序)。
还有一件事:当你只需要8个字符时,为什么你检查日期字符串的长度正好是10?
什么是例外? – hjpotter92
Test.exe中0x77383E28有一个未处理的异常:Microsoft C++的异常:std ::内存地址为0x00C7FAF4的异常 – Jek
我无法捕捉到它。 – Jek