代码之家  ›  专栏  ›  技术社区  ›  Sambatyon

小面的时间总是失败

  •  2
  • Sambatyon  · 技术社区  · 15 年前

    Unable to read cin 用一个 ios_base::iostate 等于 failbit

    #include "dates.h"
    
    #include <iostream>
    #include <ctime>
    #include <locale>
    #include <sstream>
    #include <iterator>
    
    using namespace std;
    
    void trasnlateDate(istream&in, ostream&out){
        const time_get<char>& dateReader = use_facet<time_get<char> >(in.getloc());
        ios_base::iostate state = static_cast<ios_base::iostate>(0);
        istreambuf_iterator<char> end;
    
        tm t;
    
        dateReader.get_date(in, end, in, state, &t);
    
        if(state == static_cast<ios_base::iostate>(0) || state == ios_base::eofbit){
            const time_put<char>& dateWriter = use_facet<time_put<char> >(out.getloc());
            char fmt[] = "%x";
            if(dateWriter.put(out, out, out.fill(), &t, &fmt[0], &fmt[2]).failed())
                cerr << "unable to write to output stream.\n";
        }else{
            cerr << "Unable to read cin.\n";
        }
    }
    
    int main(){
        locale::global(locale(""));
        cin.imbue(locale("en_US.utf8"));
        cout.imbue(locale("de_DE.utf8"));
        trasnlateDate(cin, cout);
    }
    

    和往常一样,Ubuntu 10.4x64中的gcc 4.4.3

    1 回复  |  直到 15 年前
        1
  •  4
  •   vhallac    15 年前

    我在一个框中运行了您的示例代码,直到我输入了2005年2月2日的输入,它才像您所说的那样失败。

    看起来月和日字段中的前导零是必需的。

    推荐文章