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 | - | 此函数在需要时用于获取区域设置刻面的流对象,例如 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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 248 | C++98 | 到达结束迭代器时未设置 eofbit |
如果未读取到有效的年份,则设置 eofbit |
[编辑] 参阅
(C++11) |
解析指定格式的日期/时间值 (函数模板) |