C++, WCHAR[] to std::cout and comparision
Asked Answered
T

4

1

I need to put WCHAR[] to std::cout ... It is a part of PWLAN_CONNECTION_NOTIFICATION_DATA passed from Native Wifi API callback.

I tried simply std::cout << var; but it prints out the numeric address of first char. the comparision (var == L"some text") doesn't work either. The debugger returns the expected value, however the comparision returns 0. How can I convert this array to a standard string(std::string)?

Thanks in advance

Tremolo answered 26/10, 2009 at 15:39 Comment(1)
THe comparison "some text"=="some text" can already fail, with plain char*. Reason: you can compare strings in C with ==. Use C++; std::wstring(L"text")==std::wstring(L"text")Jochebed
P
4

Assuming var is a wchar_t *, var == L"some text" does a pointer comparison. In order to compare the string pointed to by var, use a function such as wcscmp.

Presumption answered 26/10, 2009 at 15:50 Comment(0)
E
12

Some solutions:

  • Write to std::wcout instead
  • Convert:
    • The standard way, using std::codecvt
    • The Win32 way, using WideCharToMultibyte
Erdmann answered 26/10, 2009 at 15:44 Comment(0)
M
9

For printing to cout, you should use std::wcout instead.

As for the comparison, I'm not really sure what you mean.

  • if var is a wchar_t[], then you are comparing two pointers. And the result will most likely be false, because while the string contents may be the same, they are physically allocated in different memory locations. The answer is to either use a function like strcmp which compares C-style strings (char pointers), or to use the C++ string class.
  • and the operator== usually returns a bool, not an integer. So it can return false, but it can't return 0... Unless you've created some weird overload yourself. (and that is only possible if var is a user-defined type.
Monograph answered 26/10, 2009 at 15:46 Comment(2)
I assume you meant wcscmp? C++ really should have overloaded strcmp() to take anything stringlike. But unfortunately only the math part of the standard C library got that treatment.Jochebed
True. I meant "the strcmp family of functions". That's why I said "a function like".Monograph
P
4

Assuming var is a wchar_t *, var == L"some text" does a pointer comparison. In order to compare the string pointed to by var, use a function such as wcscmp.

Presumption answered 26/10, 2009 at 15:50 Comment(0)
W
3

use the following

#ifdef UNICODE
#define tcout wcout
#else
#define tcout cout
#endif
Waits answered 1/6, 2010 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.