c++ - facet 的 get_time 不断失败

标签 c++ g++ locale

我在这个例子中花了很多钱,每次我收到错误Unable to read cin with an ios_base::iostate equal to 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.4 x64 中的 gcc 4.4.3

最佳答案

我在一个盒子上运行了您的示例代码,直到我输入 02/02/2005 为止,它就像您所说的那样失败了。

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

关于c++ - facet 的 get_time 不断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857897/

相关文章:

javascript - Moment.js 的语言环境和特定日期格式

c++ - 一个有效,一个无效,怎么说一个有效或无效呢?

c++ - 使用 OpenCV 在 MFC/C++ 应用程序中显示图像

c++ - 未定义对vtable的引用

c++ - 与 std::chrono::system_clock/std::chrono::high_resolution_clock 的时差

c++ - 如何设置 VSCode C++ 来显示局部变量

git - 使用 Cloud9 和 Openshift 时警告 : setlocale: LC_ALL: cannot change locale (C. UTF-8)

c++ - 基于第一对的 "first"对 <std::pair<int, std::pair<int, int>>> 类型的 std::vector 进行排序的标准方法是什么

c++ - 如何使一个函数只能从另一个函数调用?

jsp - 如何从 JSP 访问 Locale?