std :: cout充满了古怪

时间:2018-04-14 05:36:11

标签: c++ locale cout

两天前,我开始编写一些我认为非常简单的代码:将日期字符串格式化为保存在mysql的DATE字段中,从“YYYY-MM-DD”格式化为用户提供的格式。从那以后,我一直陷入语言环境问题。

#include <iostream>    
#include <ctime> 

std::string fdate(std::string date, std::string format) {
        char buf[50];
        int year, month, day;
        std::tm tm;
        sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
        tm.tm_year = year - 1900;
        tm.tm_mon  = month - 1;
        tm.tm_mday = day;
//      std::cout << "std::cout locale: " << std::cout.getloc().name() << std::endl;
        strftime(buf, sizeof(buf), format.c_str(), &tm);
        return buf;
}


int main() {
        std::locale::global(std::locale(""));
        std::cout.imbue(std::locale());
        std::string format("%a %d %b %Y");
        std::string day("2018-04-14");
        std::string formatted_day = fdate(day, format);
        std::cout << "std::cout locale: " << std::cout.getloc().name() << std::endl;
        std::cout << day << "     => " << formatted_day << std::endl;
        return 0;
}

以上代码输出:

  

std :: cout locale:en_GB.utf8
     2018-04-14 =&gt; ? 2018年4月14日

请注意,“%a”应输出星期几的短英文名称,即“Sun”。取而代之的是“?”输出,因为由于某些我不理解的原因,缺少strftime()所需的语言环境信息。

如果我取消注释上述方法中注释掉的行,则输出变为:

  

std :: cout locale:en_GB.utf8
     std :: cout locale:en_GB.utf8
     2018-04-14 =&gt; Sun 2018年4月14日

在过去的两天里,我尝试了很多不同的变体,但上面的代码示例突出了一个令我困惑的事件。
为什么在方法中添加std :: cout语句“修复”问题?
有什么更好的方法来实现我最初的目标?

编辑:实际上2018-04-14是星期六!所以,我在我的代码中做了另一个错误的假设。如何填写std :: tm的缺失字段?鉴于YYYY-MM-DD日期,std库中是否有任何能够计算星期几的东西?

0 个答案:

没有答案
相关问题