![](/img/trans.png)
[英]Understanding locale class, locale::facet::_S_create_c_locale name not valid
[英]locale::facet::_S_create_c_locale name not valid for empty local name
我正在写一个 function 用于将u8string
打印到ostream
。 这就是我想出的:
auto operator<<(std::ostream& out, const std::u8string_view str) -> std::ostream& {
std::locale::global(std::locale{".utf8"});
auto& ret = out << std::string_view{std::bit_cast<const char*>(str.data()), str.size()};
std::locale::global(std::locale{""});
return ret;
}
这编译得很好。 但是在执行时,这失败了:
terminate called after throwing an instance of 'std::runtime_error'
what(): locale::facet::_S_create_c_locale name not valid
首先,我认为我的系统可能不支持".utf8"
语言环境(这是真的)。 但即使在我注释掉该行之后,我仍然遇到同样的错误。 所以错误一定是使用""
引起的。
我一直认为空的语言环境名称会将语言环境设置为用户的首选项。 如果这没有发生,我应该如何在写入ostream
后恢复用户首选的语言环境?
我正在使用g++ 12.2.0 Rev6,由Windows 11 x64上的 MSYS2 项目构建。
std::locale::global
返回以前的语言环境,因此您可以使用它来恢复它:
auto operator<<(std::ostream& out, const std::u8string_view str) -> std::ostream& {
auto locale = std::locale::global(std::locale{".utf8"});
auto& ret = out << std::string_view{std::bit_cast<const char*>(str.data()), str.size()};
std::locale::global(locale);
return ret;
}
但是你为什么首先要搞乱语言环境? 将字符写入ostream
不受语言环境的影响。 当您实际对受区域设置影响的 stream 执行某些操作时,您应该更改流的区域设置,而不是全局区域设置:
my_stream.imbue(std::locale{"en_US.utf8"})
PS:这不是bit_cast
的明智使用,您应该使用reinterpret_cast
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.