在 C/C++(ms) 中将 char[] 转换为 tchar[] 的最简单方法是什么?
这似乎是一个相当垒球的问题,但我总是很难查找这个函数,因为关于 char 和 tchar 的引用似乎有很多变化。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
最简单的方法是使用转换宏:
The simplest way is to use the conversion macros:
MSDN
TCHAR 是 Microsoft 特定的 char 或 wchar_t(宽字符)类型定义。
转换为 char 取决于它实际上是其中的哪一个。 如果 TCHAR 实际上是一个 char,那么您可以进行简单的转换,但如果它确实是一个 wchar_t,您将需要一个例程在字符集之间进行转换。 请参阅函数 MultiByteToWideChar()
TCHAR is a Microsoft-specific typedef for either char or wchar_t (a wide character).
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()
MultiByteToWideChar 但另请参阅“MultiByteToWideChar 的一些问题”。
MultiByteToWideChar but also see "A few of the gotchas of MultiByteToWideChar".
这篇文章中也有一些答案,特别是如果您正在寻找跨平台解决方案:
STL 中 UTF8 与宽字符的转换
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
最酷的事情是 equals 的两个大小都是常量,这意味着编译器将处理(并删除) if(),如果它们相等,则删除大括号内的所有内容
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
以下是将 _TCHAR * argv[] 复制为 char * argn[] 的 CPP 代码。
http://www.wincli.com/?p=72
如果您采用旧代码Windows,简单使用代码中提到的定义作为可选。
Here is the CPP code that duplicates _TCHAR * argv[] to char * argn[].
http://www.wincli.com/?p=72
If you adopting old code to Windows, simple use define mentioned in the code as optional.
您可以在代码中添加条件
ifdef _UNICODE
{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR }
You can put condition in your code
ifdef _UNICODE
{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR }
我意识到这是一个旧线程,但它没有给我“正确”的答案,所以现在添加它。
现在看来完成此操作的方法是使用 TEXT 宏。 msdn 上的 FindFirstFile 示例指出了这一点。
http://msdn.microsoft .com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx
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