49

I am little poor in typecasting. I have a string in xmlChar* (which is unsigned char*), I want to convert this unsigned char to a std::string type.

xmlChar* name = "Some data";

I tried my best to typecast , but I couldn't find a way to convert it.

donjuedo
  • 2,475
  • 18
  • 28
Cyril
  • 1,216
  • 3
  • 19
  • 40
  • 1
    `String or `std::string`? What is `String`, if you don't mean `std::string`? – Mats Petersson Jul 19 '13 at 13:01
  • Sorry @Mats Petersson, BTW its std::string – Cyril Jul 19 '13 at 13:03
  • Use reinterpret_cast See this [http://stackoverflow.com/questions/658913/c-style-cast-from-unsigned-char-to-const-char][1] [1]: http://stackoverflow.com/questions/658913/c-style-cast-from-unsigned-char-to-const-char – Ani Jul 19 '13 at 13:03
  • possible duplicate of [const unsigned char \* to std::string](http://stackoverflow.com/questions/804123/const-unsigned-char-to-stdstring) – Mats Petersson Jul 19 '13 at 13:06
  • I can see the reasons why one might want to declare `xmlChar` as an `unsigned char`. Regretfully, it doesn't work well with any of the standard library: `strlen()` and `std::string` both _require_ `char`. So if you have any influence at all, change this. (And XML using `char` is still less painful than Latin-1 using a signed `char`.) – James Kanze Jul 19 '13 at 13:15

1 Answers1

77
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.

You could also do it C-style (not recommended):

std::string sName((char*) name);
sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
  • 1
    I have found that in some cases, the reinterpret cast produces some junk characters at the end. Didn't investigate too deeply since they were easy to truncate, but I thought I'd mention it in case I'm not alone. – MatrixManAtYrService Apr 29 '16 at 22:20
  • 1
    Not alone, happened with me too – audiFanatic May 20 '16 at 22:06
  • 1
    You are probably seeing junk because your unsigned char array does not end with a null terminator (or doesn't end with one where you think it does). Generally, just casting from a type to a string type without considering NUL is dangerous and you should think about this carefully if your code is in any way different to OP's example (string **literals** have null terminators already) – David Roberts Nov 20 '16 at 15:47
  • 6
    According to this answer: https://stackoverflow.com/a/1673536/3305789 It seems that some problems can be avoided if you know the size of your string beforehand: std::string sName(reinterpret_cast(name), name_len); – dkurzaj Mar 04 '20 at 14:59