C ++: What locale do sprintf consider?

I am using the two functions sprintf and snprintf to handle the "double" to string conversions. In one case, the application that is running has a different language than the Windows locale. Thus, in such a scenario, the locale that sprintf looks at always has an application. Whereas snprintf sometimes starts using the Windows locale. As a consequence, the decimal characters returned by both methods are different and this causes a problem.

To provide more information, I have a library in my project that builds a string from "double", this library uses snprintf to convert a double to a string. Then I need to send this information to a server that would understand ". (Dot) as a decimal character only. Hence, I need to replace the local decimal character with". "(Dot). To find out the local decimal character (to replace it), I am using one of the libraries provided in my project that uses sprintf and then I replace that character with a dot to get the final result.

Also, note that sprintf always looks at the native application locale, while snprintf sometimes looks at the Windows locale. Since the problem is inconsistent, sorry for not having a clear example.

So what are the circumstances under which snprintf might behave differently? Why am I getting this behavior from these two methods? How can I avoid this?

PS - I have to use these 2 methods, so please suggest a solution that doesn't require me to use any different methods.

Thank.

+3


source to share


1 answer


The locale is used as a sprintf

, well snprintf

, is not Windows locales, but the locale of your application. Since this locale is global to your application, any line of code in your program can change it.

In your case, the (unsafe) solution might be to temporarily replace the language for the call snprintf

:



auto old = std::locale::global(std::locale::classic());
snprintf(...);
std::locale::global(old);

      

BTW, the "Windows language" can only be accessed via std::locale("")

, you don't need to know its exact name.

+4


source







All Articles