Cyril
Cyril

Reputation: 1236

convert unsigned char* to std::string

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.

Upvotes: 51

Views: 130682

Answers (2)

Maciej Kravchyk
Maciej Kravchyk

Reputation: 16697

Why not just iterate it? It's longer but you would rather want to have it as a function to use anyway.

std::string FromUnsignedCharP(const unsigned char* c_str) {
  std::string str;
  int i {0};
  while (c_str[i] != '\0') { str += c_str[i++]; }
  return str;
}

Upvotes: 0

sasha.sochka
sasha.sochka

Reputation: 14715

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);

Upvotes: 78

Related Questions