跨平台的方式转换成UTF8到std :: wstring的[复制](Cross-platform w

2019-07-19 00:29发布

可能重复:
UTF8到/从在STL宽字符转换

我知道如何UTF8转换到std ::使用wstring的的MultiByteToWideChar :

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的,有没有做同样的事情,只使用标准输入输出或iostream的一个跨平台的C ++函数?

Answer 1:

我建议使用UTF-8-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;
}


文章来源: Cross-platform way to convert UTF8 to std::wstring [duplicate]