gpt4 book ai didi

c++ - TCHAR 的二维数组

转载 作者:行者123 更新时间:2023-11-28 04:39:58 26 4
gpt4 key购买 nike

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

关于c++ - TCHAR 的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50419569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com