【问题标题】:Cross-platform way to convert UTF8 to std::wstring [duplicate]将 UTF8 转换为 std::wstring 的跨平台方法 [重复]
【发布时间】:2013-01-14 02:46:54
【问题描述】:

可能重复:
UTF8 to/from wide char conversion in STL

我知道如何使用 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?

【问题讨论】:

  • 我建议你看看像Boost locale这样的东西。
  • 我希望您的代码只是一个简单的示例代码,而不是生产代码。事实上,它不会检查来自MultiByteToWideChar() 调用的错误。此外,您可以直接在函数体内使用std::wstring,而不是在单独的std::vector 中分配内存,然后deep-copystd::wstring
  • stackoverflow.com/questions/7232710/… 的回答展示了如何使用 std::wstring_convert 类和 std::codecvt 语言环境方面来做到这一点

标签: c++ utf-8 cross-platform


【解决方案1】:

我建议使用utf8-cpp library,它很简单,而且涉及到 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2020-03-03
    • 2011-01-03
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多