Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get system's decimal separator character using STL?

Tags:

c++

stl

To generate csv files with the correct numerical separator ('.' or ','), because I want them to be compatible with Excel version installed on the machine, I need to get decimal separator character from a C++ program.

My machine has a French version of Windows/Excel, so decimal separator is ','.

int main()
{
    std::cout << std::use_facet< std::numpunct<char> >(std::cout.getloc()).decimal_point();
    return 0;
}

outputs ., which is not expected

I tried using WIN32 API:

int main()
{
    TCHAR szSep[8];
    GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, szSep, 8);
    std::cout << szSep;
}

outputs ,, which is expected.

Is there any equivalent to this GetLocaleInfo function in STL that will work inside a simple main?

like image 880
jpo38 Avatar asked Nov 07 '22 13:11

jpo38


1 Answers

Thanks to user0042 linked example, the appropriate way to do this using STL is:

int main()
{
    // replace the C++ global locale as well as the C locale with the user-preferred locale
    std::locale::global(std::locale(""));
    // use the new global locale for future wide character output
    std::cout.imbue(std::locale());

    std::cout << std::use_facet< std::numpunct<char> >(std::cout.getloc()).decimal_point();
}

outputs ,, which is expected.

Or, if you don't want to change the global:

int main()
{
    std::cout.imbue(std::locale(""));
    std::cout << std::use_facet< std::numpunct<char> >(std::cout.getloc()).decimal_point();
}
like image 154
jpo38 Avatar answered Nov 14 '22 21:11

jpo38