Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::locale loc("en_US") throw an exception?

Tags:

c++

locale

I attempting to instantiate a std::locale object with the American or British locale string.
Both std::locale loc("en_US") and std::locale loc("en_GB") throw a bad locale name runtime exception. Creating a locale using "" or "C" works fine; however, I'm having trouble setting an individual country locale.

The reason I'd like to do this is for unit testing purposes, to make sure a collection of string sorting methods work correctly.

I should also point out that I'm coding in Windows using Visual Studio 2008 and I'd like to keep my code cross-platform, if possible.

like image 923
Alan Avatar asked Jul 10 '10 22:07

Alan


2 Answers

The strings which std::locale supports are implementation specific; it could be that implementation doesn't support the string you are passing as argument.

Since you are programming in Windows, you can be interested to Language Strings, which lists the language identifiers used by setlocal, and Country/Region Strings for the country identifiers. As far as I can see, the language identifiers use a hyphen (e.g. en-US, nl-BE, and zh-HK).

You can find more information on std::locale::global(std::locale("zh-CN")) Gets "Bad locale name"??

like image 125
apaderno Avatar answered Oct 30 '22 06:10

apaderno


You better use boost.locale that uses ICU library for this. ICU provides many locales and is not dependent on OS you use. To generate std::locale you need to write:

boost::locale::generator gen;
std::locale loc = gen("en_US");

For more information: http://www.boost.org/doc/libs/1_57_0_b1/libs/locale/doc/html/index.html

like image 5
Vadim Pashaev Avatar answered Oct 30 '22 04:10

Vadim Pashaev