如何将char *转换为TCHAR []?

时间:2013-05-02 16:19:06

标签: c++ winapi visual-studio-2012 tchar

char*  stheParameterFileName = argv[1]; //I'm passing the file name as  a parameter.
TCHAR szName [512];

如何将char*转换为TCHAR []

3 个答案:

答案 0 :(得分:10)

如果包含头文件:

#include "atlstr.h"

然后您可以使用A2T宏,如下所示:

// You'd need this line if using earlier versions of ATL/Visual Studio
// USES_CONVERSION;

char*  stheParameterFileName = argv[1];
TCHAR szName [512];
_tcscpy(szName, A2T(stheParameterFileName));
MessageBox(NULL, szName, szName, MB_OK);

Details on MSDN

答案 1 :(得分:0)

表格MSDN

// convert_from_char.cpp
// compile with: /clr /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{    
// Create and display a C style string, and then use it 
// to create different kinds of strings.
char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;

// newsize describes the length of the 
// wchar_t string called wcstring in terms of the number 
// of wide characters, not the number of bytes.
size_t newsize = strlen(orig) + 1;

// The following creates a buffer large enough to contain 
// the exact number of characters in the original string
// in the new format. If you want to add more characters
// to the end of the string, increase the value of newsize
// to increase the size of the buffer.
wchar_t * wcstring = new wchar_t[newsize];

// Convert char* string to a wchar_t* string.
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE);
// Display the result and indicate the type of string that it is.
wcout << wcstring << _T(" (wchar_t *)") << endl;
...
}

TCHAR的定义取决于您使用的是Unicode还是ANSI。

另见here

通过使用Tchar.h,您可以从相同的源构建单字节,多字节字符集(MBCS)和Unicode应用程序。
Tchar.h定义宏(具有前缀_tcs),使用正确的预处理器定义,根据需要映射到str,_mbs或wcs函数。要构建MBCS,请定义符号_MBCS。要构建Unicode,请定义符号_UNICODE。要构建单字节应用程序,请不要定义(默认值) 默认情况下,为MFC应用程序定义_MBCS。 _TCHAR数据类型在Tchar.h中有条件地定义。如果为构建定义了符号_UNICODE,则_TCHAR被定义为wchar_t;,否则,对于单字节和MBCS构建,它被定义为char。 (wchar_t,基本的Unicode宽字符数据类型,是8位有符号字符的16位副本。)对于国际应用程序,使用_tcs系列函数,这些函数以_TCHAR单位运行,而不是字节。例如,_tcsncpy复制n _TCHAR,而不是n个字节。

答案 2 :(得分:0)

您的项目可能已设置为使用Unicode。 Unicode适用于想要处理地球上大多数语言的程序。如果您不需要,请转到项目属性/常规/字符集并从Unicode切换到多字节。

相关问题