Storing unicode UTF-8 string in std::string

2019-02-04 20:20发布

In response to discussion in

Cross-platform strings (and Unicode) in C++

How to deal with Unicode strings in C/C++ in a cross-platform friendly way?

I'm trying to assign a UTF-8 string to a std::string variable in Visual Studio 2010 environment

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

However, when I view the string view debugger, I only see "?????" I have the file saved as Unicode (UTF-8 with Signature) and i'm using character set "use unicode character set"

"महसुस" is a nepali language and it contains 5 characters and will occupy 15 bytes. But visual studio debugger shows msg size as 5

My question is:

How do I use std::string to just store the utf-8 without needing to manipulate it?

5条回答
乱世女痞
2楼-- · 2019-02-04 21:05

If you were using C++11 then this would be easy:

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

But since you are not, you can use escape sequences and not rely on the source file's charset to manage the encoding for you, this way your code is more portable (in case you accidentally save it in a non-UTF8 format):

std::string msg = "\xE0\xA4\xAE\xE0\xA4\xB9\xE0\xA4\xB8\xE0\xA5\x81\xE0\xA4\xB8"; // "महसुस"

Otherwise, you might consider doing a conversion at runtime instead:

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"महसुस");
查看更多
贼婆χ
3楼-- · 2019-02-04 21:18

If you set the system locale to English, and the file is in UTF-8 without BOM, VC will let you store the string as-is. I have written an article about this here.

enter image description here

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-04 21:22

There is a way to display the right values thanks to the ‘s8′ format specifier. If we append ‘,s8′ to the variable names, Visual Studio reparses the text in UTF-8 and renders the text correctly:

In case, you are using Microsoft Visual Studio 2008 Service Pack 1, you need to apply hotfix

http://support.microsoft.com/kb/980263

查看更多
戒情不戒烟
5楼-- · 2019-02-04 21:24

If you have C++11, you can write u8"महसुस". Otherwise, you'll have to write the actual byte sequence, using \xxx for each byte in the UTF-8 sequence.

Typically, you're better off reading such text from a configuration file.

查看更多
对你真心纯属浪费
6楼-- · 2019-02-04 21:25

You can write msg.c_str(), s8 in the Watches window to see the UTF-8 string correctly.

查看更多
登录 后发表回答