TCHAR的二维数组

时间:2018-05-18 21:36:09

标签: c++ windows char tchar

我尝试创建2个矩阵:1个char *和1个THAR *。但对于TCHAR *矩阵而不是字符串我得到某种地址。怎么了?

代码:

#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;
}

1 个答案:

答案 0 :(得分:1)

要解决此问题,我们需要对Unicode字符串使用wcout。使用How to cout the std::basic_string<TCHAR>,我们可以创建灵活的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;
}