跨平台的方法将UTF8转换为std::wstring

4

可能是重复问题:
如何在STL中进行UTF8到宽字符的转换

我知道如何使用MultiByteToWideChar将UTF8转换为std::wstring:

std::wstring utf8to16( const char* src )
{
    std::vector<wchar_t> buffer;
    buffer.resize(MultiByteToWideChar(CP_UTF8, 0, src, -1, 0, 0));
    MultiByteToWideChar(CP_UTF8, 0, src, -1, &buffer[0], buffer.size());
    return &buffer[0];
}

但它只适用于Windows,是否有一个跨平台的C++函数,使用stdio或iostream来完成相同的任务?


1
我建议您研究一下类似于Boost locale的东西。 - Some programmer dude
我希望你的代码只是一个简单的示例代码,而不是生产代码。实际上,它没有检查来自 MultiByteToWideChar() 调用的错误。此外,您可以在函数体内直接使用 std::wstring,而不是在单独的 std::vector 中分配内存,然后进行深层复制到 std::wstring 中。 - Mr.C64
通过 https://dev59.com/GWw05IYBdhLWcg3wcRiu 的答案,可以看到使用 std::wstring_convert 类和 std::codecvt 区域设置 facet 可以实现字符串之间的转换。 - JoergB
1个回答

3
我建议使用 utf8-cpp库,在处理utf8字符串方面,它简单直接。
该代码读取UTF-8文件并创建每行的utf16版本,然后转换回utf-8。
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "utf8.h"
using namespace std;
int main(int argc, char** argv)
{
    if (argc != 2) {
        cout << "\nUsage: docsample filename\n";
        return 0;
    }

    const char* test_file_path = argv[1];
    // Open the test file (contains UTF-8 encoded text)
    ifstream fs8(test_file_path);
    if (!fs8.is_open()) {
        cout << "Could not open " << test_file_path << endl;
        return 0;
    }

    string line;
    while (getline(fs8, line)) {

        // Convert the line to utf-16
        vector<unsigned short> utf16line;
        utf8::utf8to16(line.begin(), end_it, back_inserter(utf16line));

        // And back to utf-8
        string utf8line; 
        utf8::utf16to8(utf16line.begin(), utf16line.end(), back_inserter(utf8line));
    }
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接