Home > Net >  C reset locale to program start?
C reset locale to program start?

Time:11-06

I crawled the web a lot and got not, what I searched for even not in SO. So I consider this a new question: How to reset the locale settings to a state when the program is starting (e.g. first after main()) ?

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

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

    // 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)" << std::endl;
    return 0;
}

Output:

24500 (start)
24500 (stage1)
24500 (stage2)
24.500 (stage3)
24.500 (stage4)
24.500 (end)

The line with the "(end)" should show the same number formatting as "(start)" ...

Does anyone know how (in a general! portable?) way ?

CodePudding user response:

A few points to start with:

  • calls to std::setlocale do not affect C iostream functions, only C functions such as printf;
  • calls to std::locale::global only change what subsequent calls to std::locale() return (as far as I understand it), they do not directly affect iostream functions;
  • your call to std::wcerr.imbue does nothing since you don't use std::wcerr afterward.

To change how std::cout formats things, call std::cout.imbue. So this line at the end should work:

std::cout.imbue( std::locale("C") );

You can also reset the global locale, but that isn't useful unless you use std::locale() afterward (without arguments). This would be the line:

std::locale::global( std::locale("C") );

You can also do both in order (note no "C" in the imbue call):

std::locale::global( std::locale("C") );
std::cout.imbue( std::locale() );
  • Related