你如何获得系统在c / c ++中使用的编码类型?

在linux终端中,可以输入

locale charmap 

为了看看你的系统使用什么样的字符编码,例如UTF-8。 我的问题是如何使用c / c ++来做到这一点。 (我正在使用linux)

编辑 :我试过用

 nl_langinfo(CODESET) 

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

 SETLOCALE(3) Linux Programmer's Manual SETLOCALE(3) NAME setlocale - set the current locale SYNOPSIS #include  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  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  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). 

您必须先调用setlocale()将有关当前系统区域设置的信息填充到您的程序中,因为默认区域设置为“C”。 之后,您将能够获得系统区域设置。

这是一个例子

 #include  #include  #include  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; } 

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