为什么AfxMessageBox显示汉字
这段代码用中文显示你好,
char buffer[10]="hello";
AfxMessageBox((LPCTSTR)buffer);
而这段代码用英语显示它
AfxMessageBox(L"hello");
如果这是我的代码中的问题,有人可以告诉我如何正确键入强制转换缓冲区变量吗
This code displays hello in chinese
char buffer[10]="hello";
AfxMessageBox((LPCTSTR)buffer);
while this code displays it in english
AfxMessageBox(L"hello");
Could someone tell me how do i type cast the buffer variable properly if that is the problem in my code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
LPCTSTR 类型是指向透明字符串的长指针。
这里重要的是T,透明(至少我认为T代表透明)。
如果您的应用程序被编译为 ASCII 应用程序,则所有 T 类型(如 TCHAR)都会被重新定义为其 ASCII 对应项。所以 TCHAR 将变成简单的 char。
如果您的应用程序编译为 Unicode,则所有 T 类型都将重新定义为 Unicode 类型。 TCHAR 变为 wchar_t。
所有 Windows(和 MFC)函数也是如此。所有 Windows 函数都有 2 种变体:ASCII 版本(例如 MessageBoxA)和 Unicode 版本(例如 MessageBoxW)。 MessageBox 本身只不过是 MessageBoxA 或 MessageBoxW 的定义(取决于您的编译方式)。
在您的示例中, buffer 被定义为字符向量类型,但您将其转换为指向透明类型的指针。我假设您的应用程序是用 Unicode 编译的,因此 LPCTSTR 实际上是“wchar_t *”。所以这个演员阵容是不正确的。
在“hello”字符串前面加上 L,告诉编译器将常量“hello”作为 Unicode 字符串,这使其成为传递给 AfxMessageBox 的 Unicode 版本的正确类型。
The LPCTSTR type is a Long Pointer to a Transparent STRing.
What's important here is the T, Transparent (at least I think the T stands for Transparent).
If your application is compiled as an ASCII application, all T types (like TCHAR) are redefined as their ASCII-counterpart. So TCHAR will become simply char.
If your application is compiled as Unicode, all T types are redefined as Unicode types. TCHAR becomes wchar_t.
The same is true for all Windows (and MFC) functions. All Windows functions come in 2 variants, an ASCII version (e.g. MessageBoxA) and a Unicode version (e.g. MessageBoxW). MessageBox itself is nothing more than a define to either MessageBoxA or MessageBoxW (depending on how you compile).
In your example, buffer is defined as a char-vector type, but you convert it to a pointer to a transparent type. I assume that your application is compiled in Unicode, so LPCTSTR is actually a "wchar_t *". So this cast is incorrect.
Prepending the "hello" string with L, tells the compiler to theat the constant "hello" as a Unicode string, which makes it the correct type to be passed to the Unicode version of AfxMessageBox.
如果您在编译器选项中定义了
_UNICODE
和UNICODE
标志,则转换字符串LPCTSTR
会将字符串视为 unicode 字符串。在 Windows 中,它会将每 16 个字节视为一个字符,并尝试查找相应的 unicode 字符。要使其显示英文字符,请在定义数组时使用TCHAR
。If you have
_UNICODE
andUNICODE
flag defined in your compiler options then casting the stringLPCTSTR
will treat the string as an unicode string. In case windows, it will treat every 16 bytes as a single character and tries to find the corresponding unicode character. To make it display english character, useTCHAR
while defining the array.