Home > Mobile >  Use TCHAR still can't use std::cout ? cout should automatically get converted to wcout right?
Use TCHAR still can't use std::cout ? cout should automatically get converted to wcout right?

Time:05-19

I thought using TCHAR, and setting the character set to UNICODE in Visual Studio, maybe now I could get results in wide character ie 16 bits Unicode system, but it is not working.

This is my code:

#include<Windows.h> //to use windows API
#include<iostream>

int main()
{
    TCHAR a[] = TEXT("This is not ANSI anymore! Olé!"); //8bits each char
    wchar_t b[] = L"This is the Unicode Olé!"; //16 bits each char
    std::cout << a << "\n";
    std::wcout << b << "\n";
    return 0;
}

So I thought, after defining TCHAR, I could make use of:

#ifdef UNICODE
#define std::cout std::wcout
#else
#define std::cout std::cout
#endif

But still, my output is in hex for TCHAR a[], but why? It should use wcout automatically, right?

CodePudding user response:

std::cout does not support wchar_t strings, and std::wcout does not support char strings. So you will have to pick one or the other based on which character type TCHAR is using.

You were right to try to use #define to work around that, but you used the wrong syntax for it.

Try this instead:

#include <Windows.h> //to use windows API
#include <iostream>

#ifdef UNICODE
#define t_cout std::wcout
#else
#define t_cout std::cout
#endif

int main()
{
    TCHAR a[] = TEXT("Olé!");
    t_cout << a << TEXT("\n");
    // or: t_cout << a << std::endl;
    return 0;
}

CodePudding user response:

In Windows with UNICODE set, TCHAR comes out to wchar_t.

You can't use std::cout with wide characters. It only ever uses char. windows.h doesn't redefine cout in the way you think.

So it's as if you were outputting an array of (signed or unsigned) short to the stream. The array decays to a pointer and that's probably why you see hex.

However

std::wcout << a << "\n"; 

should work.

CodePudding user response:

The macros are not correct, also you'll need to use _setmode for a correct console output:

#include <Windows.h> //to use windows API
#include <iostream>
#include <fcntl.h>
#include <io.h>

#ifdef UNICODE
#define tcout std::wcout
#else
#define tcout std::cout
#endif

int main()
{
    _setmode(_fileno(stdout), _O_WTEXT);

    TCHAR a[] = TEXT("This is not ANSI anymore! Olé!");
    tcout << a << TEXT("\n");
}

CodePudding user response:

It's only possible for functions present in windows API , becoz your windows.h has two functions for each ANSI and unicode form and tchar whould change only for those present there.

cout and wcout not present in windows API its present in iostream so no CHANGE

  • Related