可能的重复:
STL 中 UTF8 与宽字符的转换
我知道如何使用将 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 来做同样的事情?
我建议使用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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)