2

Possible Duplicate:
How to convert pugi::char_t* to string

how can I convert pugi:char_t* type to wchar_t string?

I want to compare the result of child_value() to some utf8 string and without that convertion I cant do that.

for (pugi::xml_node_iterator it = words.begin(); it != words.end(); ++it)
    {
        wchar_t* wordValue = it->child("WORDVALUE").child_value();
    }

this assignment return error because the right side is pugi::char_t* and the left side is whar_t*

thanks

Community
  • 1
  • 1
aliakbarian
  • 709
  • 1
  • 11
  • 20
  • Going by the [documentation](http://pugixml.googlecode.com/svn/tags/latest/docs/manual/dom.html#char_t), I would use `as_wide()` as the basis, but I'd also provide an overload `as_wide(wchar_t*)` which does nothing, so you can use the function for either compiler setting. – Kerrek SB Aug 21 '11 at 20:16
  • can you tell how can I use as_wide() function? – aliakbarian Aug 21 '11 at 20:20

1 Answers1

1

Here's an idea. The crude version involves modifying the library, which may break stuff in the future, but let's begin with that:

We already have these two functions:

std::string as_utf8(const wchar_t* str);
std::wstring as_wide(const char* str);

We also know that pugi::char_t is either char or wchar_t. So all we need in order to call the conversion function on pugi::char_t is an overload, which you may add to your headers:

std::string as_utf8(const char* str) { return str; }
std::wstring as_wide(const wchar_t* str) { return str; }

Now you can write this:

pugi::char_t * mystr = get_magic_string();
std::string mystrU8 = as_utf8(mystr);

This will work in both compiler settings thanks to the overload, and if pugi::char_t is already char, then this will be optimized out entirely (assuming of course that the encoding was already UTF-8, and not any other 8-bit encoding!).

(You should also provide the overloads that take std::string and std::wstring arguments to support the same magic for pugi::string_t.)


If you worry about polluting the library, write your own wrapper:

std::string my_utf8(const char * str) { return str; }
std::string my_utf8(const wchar_t * str) { return as_utf8(str); }
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Cool. If you find the answer useful, consider accepting it :-) – Kerrek SB Aug 21 '11 at 20:49
  • I dont know if you see this comment, I use your idea and use the function as-utf8(const char *) and I get the string. actully this string is some Persian string and when I compare it to same Persian word that I had saved in utf8 textfile, the comparision doesnt work? I mean they are not same – aliakbarian Aug 22 '11 at 11:26
  • thanks. All you need is just add the functions my_utf8 in your code and do a match like : if (my_utf8(node.name())=="your node name") { ... } – superlinux Jul 07 '23 at 08:37