CString 格式 return 奇怪的字符

CString format return weird character

学生 1 的姓名打印正确 "alice",但学生 2 的姓名打印 "weird characters"。

char * student;
student = "alice";

printf("student1 : %s\n", student);

CString student2;
student2 = "alice";

student = (char *)( LPCSTR )student2;
printf("student2:%s\n", student);   

为什么在用“(char *)( LPCSTR )”转换后,它变成了 returns 奇怪的字符?

首先,这个程序对我有用。

然而,这并不意味着它是正确的。
对于 MBCS,您通常使用 _T 宏来确保正确声明您的字符串。

这是我的简单 re-write 您的代码:

#include "stdafx.h"
#include "atlstr.h"

int _tmain(int argc, _TCHAR* argv[])
{
    LPCSTR student = _T("alice");        // Use the provided LPCSTR type instead of char*.
    printf("student1 : %s\n", student);

    CString student2(_T("alice"));       // Initialize a CString with the _T macro

    student = (LPCSTR)student2;          // LPCSTR is typedef to char*. 
                                         // So you effectively had (char*)(char*)student2;
                                         // TypeCasting something twice to the same type is stupid.

    printf("student2:%s\n", student);
    return 0;
}

输出

student1 : alice
student2:alice