将 UTF8 转换为 std::wstring 的跨平台方式
Cross-platform way to convert UTF8 to std::wstring
可能的重复项:
UTF8 与 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 做同样的事情?
我建议使用 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 filenamen";
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;
}
相关文章:
- Ctypes wstring通过引用传递
- 通过网络、跨平台传递std::变体是否安全
- 如何跨平台将二进制资源构建到程序中?
- 在C++中将变量 wstring 分配给 Char 数组
- 以跨平台的方式将图像源路径从C++发送到 QML
- 跨平台 GPU 计算
- 将日语 wstring 转换为 std::string
- 在哪里存储跨平台C++应用存储?
- 使用 memcpy 将矢量数据复制到 wstring 的正确方法
- 如何将外部依赖引入跨平台CMake项目?
- 将 VS Code 用于跨平台可缩放C++项目
- 创建跨平台 C++ 触摸管理器.在 c++ 中传递 Objective-c 对象涉及代码
- 使用通配符的跨平台文件列表
- -fshort-wchar 和 std::wstring - 分段错误
- 输出 c++ 窗口 wstring 日志在终端中正确
- 如何使用跨平台代码在C++中设置系统时间?
- 跨平台 c++ 和 Visual Studio 2017?
- 跨平台随机重现性
- Boost C++ 跨平台(Windows & Mac)序列化 std::wstring
- 将 UTF8 转换为 std::wstring 的跨平台方式