简体   繁体   English

如何将 char* 转换为 std::u8string?

[英]How to convert char* into std::u8string?

Intro介绍

If I catch an exception, I want to convert the error message, which is returned as a C-style string by the what() method, into a std::u8string (a UTF-8 string).如果我捕获到异常,我想将错误消息(通过what()方法作为 C 风格字符串返回)转换为std::u8string (UTF-8 字符串)。 For example: std::u8string(error.what());例如: std::u8string(error.what());

Problem问题

How can I convert a char* into a std::u8string ?如何将char*转换为std::u8string

Additional Information附加信息

  • I only catch exceptions from the standard library, boost and eigen.我只捕获来自标准库、boost 和 eigen 的异常。
  • My application is Windows dependent, so the solution doesn't need to be portable.我的应用程序依赖于 Windows,因此该解决方案不需要可移植。

You can use the constructor that takes a beginning and an ending iterator for the sequence that defines the string.对于定义字符串的序列,您可以使用采用开始和结束迭代器的构造函数。

#include <cstring>

// ...

auto cstr=error.what();

std::u8string str{cstr, cstr+strlen(cstr)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM