c++windowschartchar

2 dimensional array of TCHAR


I try to create 2 matrices: 1 of char* and 1 of THAR*. But for TCHAR* matrix instead of strings I get addresses of some kind. What's wrong?

Code:

#include <tchar.h>
#include <iostream>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
    //char
    const char* items1[2][2] = {
        {"one", "two"},
        {"three", "four"},
    };

    for (size_t i = 0; i < 2; ++i)
    {
        cout << items1[i][0] << "," << items1[i][1] <<endl;
    }

    /*
    Correct output:
        one,two
        three,four
    */

    //TCHAR attempt
    const TCHAR* items2[2][2] = {
        {_T("one"), _T("two")},
        {_T("three"), _T("four")},
    };

    for (size_t i = 0; i < 2; ++i)
    {
        cout << items2[i][0] << "," << items2[i][1] <<endl;
    }

    /*
    Incorrect output:
        0046AB14,0046AB1C
        0046AB50,0046D8B0
    */

    return 0;
}

Solution

  • To fix the issue we need to use wcout for Unicode strings. Using How to cout the std::basic_string<TCHAR> we can create flexible tcout:

    #include <tchar.h>
    #include <iostream>
    
    using namespace std;
    
    #ifdef UNICODE
        wostream& tcout = wcout;
    #else
        ostream& tcout = cout;
    #endif // UNICODE
    
    int main(int argc, _TCHAR* argv[])
    {
        //char
        const char* items1[2][2] = {
            {"one", "two"},
            {"three", "four"},
        };
    
        for (size_t i = 0; i < 2; ++i)
        {
            tcout << items1[i][0] << "," << items1[i][1] <<endl;
        }
    
        /*
        Correct output:
            one,two
            three,four
        */
    
        //TCHAR attempt
        const TCHAR* items2[2][2] = {
            {_T("one"), _T("two")},
            {_T("three"), _T("four")},
        };
    
        for (size_t i = 0; i < 2; ++i)
        {
            tcout << items2[i][0] << "," << items2[i][1] <<endl;
        }
    
        /*
        Correct output:
            one,two
            three,four
        */
    
        return 0;
    }