Namespaces
Variants

std::time_get<CharT,InputIt>:: get_year, std::time_get<CharT,InputIt>:: do_get_year

From cppreference.net
定义于头文件 <locale>
public :

iter_type get_year ( iter_type s, iter_type end, std:: ios_base & str,

std:: ios_base :: iostate & err, std:: tm * t ) const ;
(1)
protected :

virtual iter_type do_get_year ( iter_type s, iter_type end, std:: ios_base & str,

std:: ios_base :: iostate & err, std:: tm * t ) const ;
(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 ) 范围内被识别为有效年份的最后一个字符之后位置的迭代器。

注释

对于两位数输入值,许多实现采用与转换说明符 '%y' 相同的解析规则,该说明符被 std::get_time std::time_get::get() 以及 POSIX 函数 strptime() 所使用:要求输入两位整数,范围 [ 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)
解析指定格式的日期/时间值
(函数模板)