C++ 将 unsigned char* 转换为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17746688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert unsigned char* to String
提问by Cyril
I am little poor in type casting. I have a string in xmlChar*
(which is unsigned char*), I want to convert this unsigned char to a std::string
type.
我在类型转换方面有点差。我有一个字符串xmlChar*
(它是无符号字符*),我想将此无符号字符转换为std::string
类型。
xmlChar* name = "Some data";
I tried my best to type cast , but I couldn't a way to convert it.
我尽力输入 cast ,但我无法转换它。
回答by sasha.sochka
std::string sName(reinterpret_cast<char*>(name));
reinterpret_cast<char*>(name)
casts from unsigned char*
to char*
in an unsafe way but that's the one which should be used here. Then you call the ordinary constructor of std::string
.
reinterpret_cast<char*>(name)
unsigned char*
以char*
一种不安全的方式从to转换,但这是应该在这里使用的方式。然后调用 的普通构造函数std::string
。
You could also do it C-style (not recommended):
你也可以做 C 风格的(不推荐):
std::string sName((char*) name);