C++ 在std::string中存储unicode UTF-8字符串

C++ 在std::string中存储unicode UTF-8字符串,c++,windows,unicode,utf-8,stdstring,C++,Windows,Unicode,Utf 8,Stdstring,回应在 我正在尝试将UTF-8字符串分配给visualstudio2010环境中的std::string变量 std::string msg=”महसुस"; 但是,当我查看字符串视图调试器时,我只看到“??” 我将文件保存为Unicode(带签名的UTF-8) 我正在使用字符集“使用unicode字符集” "महसुस是一种尼泊尔语言,包含5个字符,将占用15个字节。但visual studio调试器将msg大小显示为5 我的问题是: 我如何使用std::string只存储utf-8而不需

回应在

我正在尝试将
UTF-8
字符串分配给
visualstudio2010
环境中的
std::string
变量

std::string msg=”महसुस";

但是,当我查看字符串视图调试器时,我只看到“??” 我将文件保存为Unicode(带签名的UTF-8) 我正在使用字符集“使用unicode字符集”

"महसुस是一种尼泊尔语言,包含5个字符,将占用15个字节。但visual studio调试器将msg大小显示为5

我的问题是:


我如何使用std::string只存储utf-8而不需要对其进行操作?

如果您有C++11,您可以编写
u8“महसुस“
。否则,您必须为UTF-8序列中的每个字节使用
\xxx
写入实际的字节序列


通常,您最好从配置文件中读取此类文本。

您可以编写
msg.c_str(),s8
,以正确查看UTF-8字符串。

有一种方法可以显示正确的值,这要归功于's8'。如果我们将's8'附加到变量名,Visual Studio将重新解析UTF-8中的文本并正确呈现文本:

如果您使用的是Microsoft Visual Studio 2008 Service Pack 1,则需要应用修补程序


如果您使用的是C++11,那么这将很容易:

std::string msg = u8"महसुस";
但由于您不是,因此可以使用转义序列,而不依赖源文件的字符集为您管理编码,这样您的代码更便于移植(以防您意外地将其保存为非UTF8格式):

否则,您可能会考虑在运行时进行转换:

std::string toUtf8(const std::wstring &str)
{
    std::string ret;
    int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0, NULL, NULL);
    if (len > 0)
    {
        ret.resize(len);
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), &ret[0], len, NULL, NULL);
    }
    return ret;
}


我没有C++11,从配置文件中读取这样的文本有什么区别?@PriteshAcharya您可以从编译器可能解释它的方式中解放出来。另外:如果您想提供多个不同的翻译,这是必要的。我使用的是Visual Studio 2010,因为我没有C++11,使用“s8”格式说明符会给我补偿iler错误通过添加“pragma执行字符集”(“utf-8”)重试无效。我得到了相同的结果这是命令窗口的结果:
?msg.c_str(),s8“???”>?msg.c_str(),su”㼿㼿?坎劲䤪⸭䬩⧌啍噉촀췍﷽﷽ꮫꮫꮫꮫﻮﻮ“
@PriteshAcharya:
s8
用于UTF-8,
su
用于多字节unicode字符集。@PriteshAcharya:btw,如果您有”使用unicode字符集““在您的配置中,您如何知道您正在分配UTF-8字符串?实际上,我不知道您的问题的答案。我从另一个源代码获得UTF-8并粘贴到源代码中。我的文件编码为UTF-8。确保赋值是UTF-8字符串还不够吗?@PriteshAcharya:如果在项目中使用多字节字符集-是,如果不使用-否。
std::string toUtf8(const std::wstring &str)
{
    std::string ret;
    int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0, NULL, NULL);
    if (len > 0)
    {
        ret.resize(len);
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), &ret[0], len, NULL, NULL);
    }
    return ret;
}
std::string msg = toUtf8(L"महसुस");