Search code examples
c++stringlocale

swprintf locale


using c++ on windows,

trying to set the locale to be used by the swprintf function.

i need to include the thousand separator with the number which is printed out.

i tried several options...

_wsetlocale(LC_NUMERIC, L""); //default locale

also..

_wsetlocale(LC_NUMERIC, L"english");

and of course..

swprintf(buf, L"%d", 3546);

i also tried to display the number as follows

auto locale = _get_current_locale();
_swprintf_l(buf, L"%d", locale, 3546);

i need to get the thousands separator, i.e 3,456

i also placed a breakpoint to see the value of the locale variable, it contains the lconv struct with the thousands separator correctly set to , ... however, swprintf is ignoring it.


Solution

  • Tested on Linux

    Try with that :

    setlocale(LC_NUMERIC, "en_US.ISO8859-1");
    

    Example :

    #include <stdio.h>
    #include <time.h>
    #include <locale.h>
    
    int main(void)
    {
            setlocale(LC_NUMERIC, "en_US.iso88591");
            printf("%'d (%s)\n", 12345, setlocale(LC_NUMERIC, NULL));
            return 0;
    }
    

    You are missing the ' use %'d and not %d

    Still working with wchar

    #include <stdio.h>
    #include <time.h>
    #include <locale.h>
    #include <wchar.h>
    
    int main(void)
    {
            setlocale(LC_NUMERIC, "en_US.iso88591");
            wprintf(L"%'d\n", 12345);
            return 0;
    }
    

    An other example :

    #include <stdio.h>
    #include <time.h>
    #include <locale.h>
    #include <wchar.h>
    
    int main(void)
    {
            wchar_t buf[32];
            setlocale(LC_NUMERIC, "en_US.iso88591");
            swprintf(buf, 32, L"%'d", 12345);
            wprintf(L"%ls\n", buf);
            return 0;
    }
    

    Windows

    Well today I did test on Windows (with mingw) and this is not implemented... Please read this link, which provides a solution http://c-faq.com/stdio/commaprint.html