C++ 将语言环境重置为程序启动时的状态?

Jes*_*sko 1 c++ locale

我在网上爬了很多遍,但没有得到,我搜索的内容甚至不在SO中。所以我认为这是一个新问题:如何将区域设置重置为程序启动时的状态(例如,在 main() 之后首先)?

int
main( int argc, char **argv )
{
    // this is start output I like to have finally again
    std::cout << 24500 << " (start)\n";

    // several modifications ... [e.g. arbitrary source code that cannot be changed]
    std::setlocale( LC_ALL, "" );
    std::cout << 24500 << " (stage1)\n";
    std::locale::global( std::locale( "" ) );
    std::cout << 24500 << " (stage2)\n";
    std::cout.imbue( std::locale() );
    std::cout << 24500 << " (stage3)\n";
    std::wcerr.imbue( std::locale() );
    std::cout << 24500 << " (stage4)\n";

    // end ... here goes the code to reset to the entry-behaviour (but won't work so far)
    std::setlocale( LC_ALL, "C" );
    std::locale::global( std::locale() );
    std::cout << 24500 << " (end)\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

24500 (start)
24500 (stage1)
24500 (stage2)
24.500 (stage3)
24.500 (stage4)
24.500 (end)
Run Code Online (Sandbox Code Playgroud)

带有“(结束)”的行应显示与“(开始)”相同的数字格式...

有谁知道如何(一般!便携式?)方式?

Nel*_*eal 5

可以从以下几点入手:

  • 调用std::setlocale不会影响 C++iostream函数,只会影响 ; 等 C 函数printf
  • 调用std::locale::global仅更改后续调用返回的内容std::locale()(据我了解),它们不会直接影响iostream函数;
  • 您的调用std::wcerr.imbue不会执行任何操作,因为您之后不使用std::wcerr

要更改std::cout事物的格式,请调用std::cout.imbue. 所以最后这一行应该有效:

std::cout.imbue( std::locale("C") );
Run Code Online (Sandbox Code Playgroud)

您还可以重置全局区域设置,但这没有用,除非您std::locale()随后使用(不带参数)。这将是一行:

std::locale::global( std::locale("C") );
Run Code Online (Sandbox Code Playgroud)

您也可以按顺序执行这两项操作(请注意通话"C"中的“否imbue”):

std::locale::global( std::locale("C") );
std::cout.imbue( std::locale() );
Run Code Online (Sandbox Code Playgroud)