【问题标题】:2 dimensional array of TCHARTCHAR 的二维数组
【发布时间】:2018-05-18 21:36:09
【问题描述】:

我尝试创建 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;
}

【问题讨论】:

  • 请只标记您使用的语言。
  • 假设您在启用 unicode 的情况下进行编译,请使用 wcout 作为您的第二组。
  • TCHAR 是一只奇怪的野兽。这是 ASCII 和 Unicode 之间过渡时期的残余。根据通常设置为编译器参数的#defineTCHAR 可能是 8 位或 16 位宽。在这个更开明的时期,你最好全部使用 ASCII 或 Unicode(你应该更喜欢后者),根本不使用 TCHAR
  • @WhozCraig 是的,它奏效了。对此添加了我自己的答案。

标签: c++ windows char tchar


【解决方案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;
}

【讨论】:

  • tcout 放入std 命名空间是一种非常糟糕的形式。总有一天可能会给你带来麻烦。
  • @MarkRansom 如何做得更好?
  • 如果你把它放在std命名空间里是不是不行?
猜你喜欢
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2019-01-23
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多