将UTF8转换为std :: wstring的跨平台方式 [英] Cross-platform way to convert UTF8 to std::wstring

查看:421
本文介绍了将UTF8转换为std :: wstring的跨平台方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
UTF8与STL中的宽字符转换之间

Possible Duplicate:
UTF8 to/from wide char conversion in STL

我知道如何使用但是它特定于Windows,是否存在仅使用stdio或iostream来完成相同功能的跨平台C ++函数?

but it is Windows-specific, is there a cross-platform C++ function that does the same thing, using only stdio or iostream?

推荐答案

我建议使用 utf8-cpp库,它很简单,而且涉及到utf8字符串.

i suggest using utf8-cpp library it is simple and to the point when it comes to utf8 strings .

此代码读取UTF-8文件并创建每行的utf16版本,然后转换回utf-8

this code reads UTF-8 file and creates a utf16 version of each line, then converts back to 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;
}

这篇关于将UTF8转换为std :: wstring的跨平台方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆