Why does std::locale loc("en_US") throw an exception?
I attempting to instantiate a std::locale
object with the American or British locale string.
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开发者_StackOverflow 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.
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"??
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
精彩评论