Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Which locale is considered by sprintf?

I am using two functions sprintf and snprintf for dealing with conversions of "double" to string, In one of the case, the application which is running has a different locale than the Windows' locale. So, in such a scenario locale which is considered by sprintf is always of the application. Whereas, snprintf sometimes starts using Windows locale. As a consequence of this, decimal characters returned by both the methods are different and it causes a problem.

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

Also, please note, sprintf is always considering locale of native application while snprintf sometimes considers locale of Windows. As the problem is inconsistent, sorry for not providing a clear example.

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

P.S. - I have to use these 2 methods, so please suggest a solution which would not require me to use any different methods.

Thanks.

like image 287
Prasad Avatar asked Dec 19 '14 09:12

Prasad


1 Answers

The locale used by both sprintf and snprintf is not the Windows locale, but your application locale. As this locale is global to your application, any line of code in your program can change it.

In your case, the (not thread safe) solution may be to temporarily replace the locale for the snprintf call:

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

BTW, the "Windows locale" can be accessed via just std::locale("") , you don't need to know its exact name.

like image 164
MSalters Avatar answered Oct 05 '22 03:10

MSalters