【问题标题】:How do you get what kind of encoding your system uses in c/c++?您如何获得系统在 c/c++ 中使用的编码类型?
【发布时间】:2009-09-29 14:30:06
【问题描述】:

在 linux 终端中键入

locale charmap

为了查看您的系统使用哪种字符编码,例如 UTF-8。 我的问题是你将如何使用 c/c++ 来做到这一点。 (我用的是linux)

编辑:我尝试使用

nl_langinfo(CODESET)

但我得到的是 ANSI_X3.4-1968 而不是 UTF-8(这是我在输入时得到的:locale charmap)。我使用 nl_langinfo() 是不是错了?

【问题讨论】:

    标签: c++ c character-encoding


    【解决方案1】:
    SETLOCALE(3)               Linux Programmer’s Manual              SETLOCALE(3)
    
    NAME
           setlocale - set the current locale
    
    SYNOPSIS
           #include <locale.h>
    
           char *setlocale(int category, const char *locale);
    
    DESCRIPTION
           The  setlocale() function is used to set or query the program’s current
           locale.
    

    NL_LANGINFO(3)             Linux Programmer’s Manual            NL_LANGINFO(3)
    
    NAME
           nl_langinfo - query language and locale information
    
    SYNOPSIS
           #include <langinfo.h>
    
           char *nl_langinfo(nl_item item);
    
    DESCRIPTION
           The  nl_langinfo()  function provides access to locale information in a
           more flexible way than localeconv(3) does.  Individual  and  additional
           elements  of  the locale categories can be queried.  setlocale(3) needs
           to be executed with proper arguments before.
           Examples for the locale elements that can be specified  in  item  using
           the constants defined in <langinfo.h> are:
    
           CODESET (LC_CTYPE)
              Return  a string with the name of the character encoding used in
              the  selected  locale,  such  as   "UTF-8",   "ISO-8859-1",   or
              "ANSI_X3.4-1968"  (better  known as US-ASCII).  This is the same
              string that you get with "locale charmap".  For a list of  char‐
              acter encoding names, try "locale -m", cf. locale(1).
    

    【讨论】:

    • nl lang info 似乎要求您指定语言环境并返回详细信息,它不会告诉您语言环境是什么。因此,为什么我删除了我的答案并赞成你的答案:)
    • 如果您在手册页中包含CODESET (LC_CTYPE) ... same string that you get with "locale charmap" 的位会更好地回答这个问题
    • 这太棒了!我想这正是我想要的!我试试看,thx~~
    【解决方案2】:

    您必须首先调用 setlocale() 来将有关当前系统语言环境的信息填充到您的程序中,因为默认情况下语言环境是“C”。之后,您将能够获取系统语言环境。

    这里是例子

    #include <stdio.h>
    #include <locale.h>
    #include <langinfo.h>
    
    int main()
    {
            setlocale(LC_ALL, "");
            char* locstr = setlocale(LC_CTYPE, NULL);
            char* encoding = nl_langinfo(CODESET);
            printf("Locale is %s\n", locstr);
            printf("Encoding is %s\n", encoding);
            return 0;
    }
    

    【讨论】:

      【解决方案3】:

      通常,您不会明确地这样做。相反,您将程序设置为使用名为“”的语言环境。这将为您提供系统设置使用的任何语言环境。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-10
        • 2011-12-11
        相关资源
        最近更新 更多