std::time_get<CharT,InputIt>::get_year, std::time_get<CharT,InputIt>::do_get_year
来自 cppreference.cn
定义于头文件 <locale> |
||
public: iter_type get_year( iter_type s, iter_type end, std::ios_base& str, |
(1) | |
protected: virtual iter_type do_get_year( iter_type s, iter_type end, std::ios_base& str, |
(2) | |
1) 公有成员函数,调用最终派生类的受保护虚成员函数
do_get_year
。2) 从序列
[
beg,
end)
中读取连续字符,并使用某种实现定义的格式解析出年份。根据区域设置,可能接受两位数年份,且其所属世纪为实现定义的。解析出的年份存储在 std::tm 结构体字段 t->tm_year 中。
如果在读取有效年份之前到达了尾后迭代器,则此函数在 err 中设置 std::ios_base::eofbit。如果遇到解析错误,则此函数在 err 中设置 std::ios_base::failbit。
内容 |
[编辑] 参数
beg | - | 指示要解析的序列的起始迭代器 |
end | - | 要解析的序列的尾后迭代器 |
str | - | 此函数在需要时用于获取区域设置 facet 的流对象,例如 std::ctype 用于跳过空白符,或 std::collate 用于比较字符串 |
err | - | 流错误标志对象,此函数会修改它以指示错误 |
t | - | 指向 std::tm 对象的指针,该对象将保存此函数调用的结果 |
[编辑] 返回值
迭代器,指向 [
beg,
end)
中被识别为有效年份一部分的最后一个字符之后的位置。
[编辑] 注解
对于两位数输入值,许多实现使用与 std::get_time、std::time_get::get() 和 POSIX 函数 strptime()
使用的转换说明符 '%y' 相同的解析规则:预期为两位数整数,范围 [
69,
99]
中的值产生 1969 到 1999 的值,范围 [
00,
68]
中的值产生 2000 到 2068。四位数输入通常按原样接受。
如果遇到解析错误,则此函数的大多数实现会保持 *t 不修改。
[编辑] 示例
运行此代码
#include <iostream> #include <iterator> #include <locale> #include <sstream> void try_get_year(const std::string& s) { std::cout << "Parsing the year out of '" << s << "' in the locale " << std::locale().name() << '\n'; std::istringstream str(s); std::ios_base::iostate err = std::ios_base::goodbit; std::tm t; std::time_get<char> const& facet = std::use_facet<std::time_get<char>>(str.getloc()); std::istreambuf_iterator<char> ret = facet.get_year({str}, {}, str, err, &t); str.setstate(err); std::istreambuf_iterator<char> last{}; if (str) { std::cout << "Successfully parsed, year is " << 1900 + t.tm_year; if (ret != last) { std::cout << " Remaining content: "; std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout)); } else std::cout << " the input was fully consumed"; } else { std::cout << "Parse failed. Unparsed string: "; std::copy(ret, last, std::ostreambuf_iterator<char>(std::cout)); } std::cout << '\n'; } int main() { std::locale::global(std::locale("en_US.utf8")); try_get_year("13"); try_get_year("2013"); std::locale::global(std::locale("ja_JP.utf8")); try_get_year("2013年"); }
可能的输出
Parsing the year out of '13' in the locale en_US.utf8 Successfully parsed, year is 2013 the input was fully consumed Parsing the year out of '2013' in the locale en_US.utf8 Successfully parsed, year is 2013 the input was fully consumed Parsing the year out of '2013年' in the locale ja_JP.utf8 Successfully parsed, year is 2013 Remaining content: 年
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 248 | C++98 | 到达尾后迭代器时未设置 eofbit |
若尚未读取有效年份则设置 eofbit |
[编辑] 参见
(C++11) |
解析指定格式的日期/时间值 (函数模板) |