How to get the locale of the current user in OSX using C++

时间:2016-08-31 17:26:04

标签: c++ macos

I have a C++ application where I need to retrieve the locale of the current user. How can I do it with OSX Yosemite and newer?

I've tried something like setlocale(LC_CTYPE, NULL); but it just returns UTF-8 where my system is clearly in Spanish (es_AR)

1 个答案:

答案 0 :(得分:1)

After some try and error and lot of help from internet and other questions I did it.

If I want to get only the language.

CFLocaleRef cflocale = CFLocaleCopyCurrent();
CFStringRef value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleLanguageCode); 
std::string str(CFStringGetCStringPtr(value, kCFStringEncodingUTF8));
CFRelease(cflocale);

This way, at str I'll get a std::string with the language. If I need something else, I can replace kCFLocaleLanguageCode with any other constant from CFLocale

Also I needed the header #import <CoreFoundation/CoreFoundation.h>