C++使用自定义区域设置的小写字符串

lpa*_*s12 8 c++ locale tolower

我一直试图std::tolower()用不同的语言环境调用,但似乎出现了问题.我的代码如下:

int main() {
    std::locale::global(std::locale("es_ES.UTF-8"));
    std::thread(&function, this); // Repeated some times
    // wait for threads
}

void function() {
    std::string word = "HeÉllO";
    std::transform(word.begin(), word.end(), word.begin(), cToLower);
}

int cToLower(int c) {
    return std::tolower(c, std::locale());
}
Run Code Online (Sandbox Code Playgroud)

所以当我尝试执行这个程序时,我得到:

terminate called after throwing an instance of 'std::bad_cast'
terminate called recursively
  what():  std::bad_cast
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

虽然执行return std::tolower(c);工作正常,但它只是将'标准'字符转换为较低的,而不是É.

我有一些线程同时执行相同的功能,使用C++ 11并使用g ++进行编译(如果它与它有关).

我想知道这是否是实现我想做的正确方法,或者还有其他一些方法.

谢谢!

j2k*_*2ko 1

检查您的系统上是否安装了您尝试使用的区域设置。例如,我必须在下面的代码停止崩溃之前安装西班牙语语言环境。\n此外,您可以使用它wstring。\n更新:经过一番挖掘后,这里很好地解释了使用wstring- 所有缺点和过程(主要是缺点)。

\n\n
#include <thread>\n#include <locale>\n#include <algorithm> \n#include <iostream>\n\n//forward declaration\nvoid function();\n\nint main() {\n    std::locale::global(std::locale("es_ES.utf8"));\n    std::thread test(&function);\n    test.join();\n}\n\nwchar_t cToLower(wchar_t c) {        \n    return std::tolower(c, std::locale());    \n}\n\nvoid function() {\n    std::wstring word = L"He\xc3\x89llO";\n    std::transform(word.begin(), word.end(), word.begin(), cToLower);\n    std::wcout << word;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
he\xc3\xa9llo\n
Run Code Online (Sandbox Code Playgroud)\n