简体   繁体   English

在C / C ++(ms)中将char []转换为/从tchar []的最简单方法是什么?

[英]What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?

这似乎是一个非常柔软的问题,但我总是很难查找这个函数,因为似乎有很多关于char和tchar的引用的变化。

The simplest way is to use the conversion macros: 最简单的方法是使用转换宏:

  • CW2A CW2A
  • CA2W CA2W
  • etc... 等等...

MSDN MSDN

TCHAR is a Microsoft-specific typedef for either char or wchar_t (a wide character). TCHAR是特定于Microsoft的typedef,用于char或wchar_t(宽字符)。

Conversion to char depends on which of these it actually is. 转换为char取决于它实际上是哪一个。 If TCHAR is actually a char, then you can do a simple cast, but if it is truly a wchar_t, you'll need a routine to convert between character sets. 如果TCHAR实际上是一个char,那么你可以做一个简单的转换,但如果它真的是一个wchar_t,你需要一个例程来在字符集之间进行转换。 See the function MultiByteToWideChar() 查看函数MultiByteToWideChar()

There are a few answers in this post as well, especially if you're looking for a cross-platform solution: 这篇文章也有一些答案,特别是如果你正在寻找一个跨平台的解决方案:

UTF8 to/from wide char conversion in STL UTF8到/来自STL中的宽字符转换

Although in this particular situation I think the TChar is a wide character I'll only need to do the conversion if it isn't. 虽然在这种特殊情况下,我认为TChar是一个广泛的角色,如果不是,我只需要进行转换。 which I gotta check somehow. 我得以某种方式检查。

if (sizeof(TCHAR) != sizeof(wchar_t))
{  .... }

The cool thing about that is both sizes of the equals are constants, which means that the compiler will handle (and remove) the if(), and if they are equal, remove everything inside the braces 很酷的是,equals的大小都是常量,这意味着编译器将处理(并删除)if(),如果它们相等,则删除大括号内的所有内容

Here is the CPP code that duplicates _TCHAR * argv[] to char * argn[]. 以下是将_TCHAR * argv []复制到char * argn []的CPP代码。

http://www.wincli.com/?p=72 http://www.wincli.com/?p=72

If you adopting old code to Windows, simple use define mentioned in the code as optional. 如果您将旧代码应用于Windows,则可以使用代码中提到的简单定义作为可选。

You can put condition in your code 你可以在你的代码中加入条件

ifdef _UNICODE ifdef _UNICODE

{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR } {//像TCHAR一样宽大的问候}以及{//做像TCHAR是CHAR}

I realize this is an old thread, but it didn't get me the "right" answer, so am adding it now. 我意识到这是一个老线程,但它并没有让我得到“正确”的答案,所以我现在就加入它。

The way this appears to be done now is to use the TEXT macro. 现在看来这样做的方法是使用TEXT宏。 The example for FindFirstFile at msdn points this out. msdn的FindFirstFile示例指出了这一点。 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM