Question

I have a situation where I need to compare a char* with a WideString.
How do I convert the WideString to a char* in C++?

Was it helpful?

Solution

OTHER TIPS

Not possible. Actually, you mixed two different concepts:

  • Widestring implies a buffer in UTF-16 encoding.
  • char* may contain anything, from UTF-8 to ASCII-only text (in which case, this is convertable only if your widestring does not contain non-ASCII characters).

Please see my answer to https://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful about how to properly handle text.

To compare a System::WideString object with a char* (as the question body says you want to do), you can create a new WideString object from the pointer and then use ordinary == operator. The class has several constructors, including one for const char*.

char* foo = ...;
WideString bar = ...;
if (WideString(foo) == bar)
  std::cout << "They're equal!\n";

In fact, as long as the WideString object is on the left, you don't even need the constructor call because the pointer will be converted automatically.

if (bar == foo) { ... }

To convert a WideString to a char* (as the question title says you want to do), you might consider using the AnsiString type. They're convertible between each other. To get the ordinary pointer, call the c_str method, just like you would with std::string.

WideString bar = ...;
AnsiString foo = bar;
std::cout << foo.c_str();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top