9

I'm quite sure that it is a stupid issue but it drives me crazy..

how could i print on the console a TCHAR array?

DWORD error = WSAGetLastError();
TCHAR errmsg[512];
int ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, 0, errmsg, 511, NULL);

i need to print errmsg...

hara
  • 3,274
  • 4
  • 37
  • 55
  • Even if you get your program to write UTF16 correctly to the console, Note that the Windows console isn't UTF16 friendly and may just show garbage. See this question for workarounds: http://stackoverflow.com/q/10764920/845092 – Mooing Duck Dec 16 '14 at 21:59

4 Answers4

15

It depends on what TCHAR is. If you compile with Unicode enabled, TCHAR is defined as wchar_t. Then you can use std::wcout, for example:

std::wcout << L"Error: " << errmsg << '\n';

If Unicode is not enabled, TCHAR is an ordinary char and you can use the ordinary std::cout:

std::cout << "Error: " << errmsg << '\n';
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 9
    What's the point in even using TCHAR if you're going to make your program dependent on whether its a `char` or a `wchar_t`? The whole point of it is to work regardless of what character set you're using, right? – Strigoides Feb 23 '14 at 22:28
  • @Strigoides: It's pretty common to assume `TCHAR` == `wchar_t`. Pretty much nobody uses `TCHAR`==`char`. I agree with it being pointless, but I think it _is_ the norm, especially for those still using MFC. – Mooing Duck Dec 16 '14 at 21:57
  • 4
    For this you must use **tprintf** family, this way it is not dependent on wheather **TCHAR** is **char** or **wchar** – hdkrus Nov 14 '15 at 15:07
7

A Google search revealed this discussion which essentially recommends tprintf.

Jacob
  • 34,255
  • 14
  • 110
  • 165
5
#include <tchar.h> /* _tprintf */

DWORD dwError;
BOOL fOk;
HLOCAL hlocal = NULL; // Buffer that gets the error message string

fOk = FormatMessage(
  FORMAT_MESSAGE_FROM_SYSTEM |
  FORMAT_MESSAGE_IGNORE_INSERTS |
  FORMAT_MESSAGE_ALLOCATE_BUFFER,
  NULL, dwError, 0, (PTSTR) &hlocal, 0, NULL);
if (! fOk) hlocal = TEXT("Fehler FormatMessage");
_tprintf( TEXT("%d\t%s\n"), dwError, hlocal );
if (fOk) LocalFree(hlocal);
Lumi
  • 14,775
  • 8
  • 59
  • 92
-3

I really don't know why but this code worked for me:

TCHAR NPath[MAX_PATH];
    DWORD a = GetCurrentDirectory(MAX_PATH, NPath);
    string b = "";
    for(int i=0; i<a;i++){
        b+=NPath[i];
    }
    cout << b;
    system("pause");

Sorry but i can't really explain why it works and don't have time to search it now. Later!