在 C/C++(ms) 中将 char[] 转换为/从 tchar[] 的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/159442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?
提问by CrashCodes
This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar.
这似乎是一个相当不错的垒球问题,但我总是很难查找这个函数,因为在引用 char 和 tchar 方面似乎有很多变化。
采纳答案by jeffm
回答by RichS
回答by Chris Johnson
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. 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. See the function MultiByteToWideChar()
转换为 char 取决于它实际上是其中的哪一个。如果 TCHAR 实际上是一个字符,那么你可以做一个简单的转换,但如果它真的是一个 wchar_t,你将需要一个例程来在字符集之间进行转换。参见函数 MultiByteToWideChar()
回答by Mark Ransom
There are a few answers in this post as well, especially if you're looking for a cross-platform solution:
这篇文章中也有一些答案,特别是如果您正在寻找跨平台解决方案:
回答by James Curran
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. which I gotta check somehow.
尽管在这种特殊情况下,我认为 TChar 是一个宽字符,但如果不是,我只需要进行转换。我必须以某种方式检查。
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(),如果它们相等,则删除大括号内的所有内容
回答by Dmitry Obukhov
Here is the CPP code that duplicates _TCHAR * argv[] to char * argn[].
这是将 _TCHAR * argv[] 复制到 char * argn[] 的 CPP 代码。
If you adopting old code to Windows, simple use define mentioned in the code as optional.
如果您采用旧代码到 Windows,简单使用将代码中提到的定义为可选。
回答by chandan
You can put condition in your code
您可以在代码中添加条件
ifdef _UNICODE
ifdef _UNICODE
{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR }
{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR }
回答by John
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. The example for FindFirstFile at msdn points this out. http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx
现在看来这样做的方法是使用 TEXT 宏。msdn 上的 FindFirstFile 示例指出了这一点。 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx