简体   繁体   English

C ++在整个程序中设置Locale

[英]C++ Set Locale across the entire program

I"m looking for a way to set the locale across the entire program, if that"s even possible. 我正在寻找一种在整个程序中设置语言环境的方法,如果可能的话。

I set the locale in my main function like this: 我在我的main函数中设置了这样的语言环境:

int main()
{
    setlocale(LC_ALL, "");
    ....
    return 0;
}

However, it doesn"t set the locale to my different classes/methods across the entire program. I"d rather not write this line on top of every method that will print on the screen and creating a C++ locale object and passing it around doesn"t quite feel acceptable. 但是,它并没有在整个程序中将语言环境设置为我的不同类/方法。我宁愿不在每个将在屏幕上打印并创建C ++语言环境对象并传递给它的方法之上编写此行。 “我觉得很可以接受。

Thank you for your time. 感谢您的时间。

The two functions that modify global locale settings are std::setlocale and std::locale::global . 修改全局语言环境设置的两个函数是std :: setlocalestd :: locale :: global All future C and C++ I/O and string manipulation will use them, except for the six standard I/O C++ streams, which are constructed before your code runs, so you may have to imbue them individually if so desired: 所有未来的C和C ++ I / O和字符串操作都将使用它们,除了在代码运行之前构造的六个标准I / O C ++流,因此如果需要,您可能必须单独填充它们:

#include <locale>
#include <clocale>
int main()
{
   std::setlocale(LC_ALL, ""); // for C and C++ where synced with stdio
   std::locale::global(std::locale("")); // for C++
   std::cout.imbue(std::locale());
   // cerr, clog, wcout, wcerr, wclog as needed

setlocale used for setting the locale, but its scope if decided by the first parameter (ie flag) that we pass. setlocale用于设置语言环境,但其范围由我们传递的第一个参数(即标志)决定。 In your case, "LC_ALL". 在你的情况下,“LC_ALL”。

There are two ways to set the locale. 有两种方法可以设置区域设置。 So, as per behavior of the setlocale, if you pass second parameter as "" or NULL, it takes the default from the system enviornment ( LANG ). 因此,根据setlocale的行为,如果将第二个参数作为“”或NULL传递,则它采用系统环境( LANG )的默认值。 Code for reference as below: 代码参考如下:

setenv("LANG","en_US.utf8",1);
cout << "GET ENV .... " << getenv("LANG");
setlocale(LC_ALL,"");

The other way is to use the locale, as below: 另一种方法是使用语言环境,如下所示:

setlocale(LC_ALL,"en_US.utf8");

Code Illustration 代码图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM