有关CString 与char *的转换

C++语言 码拜 8年前 (2016-04-01) 1341次浏览
最近在整理复习CString和char *的事情,写测试程序,大意就是做两件事情:让cstring转char *,然后再转回来。
代码如下:

#include "stdafx.h"
#include "afx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	CString s1 = "test123";
	char *p = (LPSTR)(LPCTSTR)s1;    //cstring转char *
	CString s2 = p;                                 //char *转cstring
	cout<<"cout *p: "<<*p<<endl;
	cout<<"cout  p: "<<p<<endl;
	cout<<"cout s2: "<<s2<<endl;
	cin.get();
	return 0;
}

得到的结果是:

cout *p: t
cout  p: t
cout s2: 0094FEC8

有如下问题讨教大家:
1. 为什么cout *p和cout p是一样的,而且只输出了字符串的第一个字符?
2. 为什么cout s2的结果是地址?
3. 本人的两步转换在程序上能否正确?
谢谢大家!

解决方案

60

选这个再测试即可:
有关CString 与char *的转换

10

char*转CString:除了直接赋值外,还可使用CString::Format进行。如char * p=”sfdasf”;CString str=p; 或str.Format(“%s”,p);CString 转char *1.直接强制类型转换: CString ss=”sfasf”;  char *p=(LPSTR)(LPCSTR)ss;2.CString::GetBuffer或LockBufferchar * p=str.GetBuffer();char * pt=str.LockBuffer();

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明有关CString 与char *的转换
喜欢 (0)
[1034331897@qq.com]
分享 (0)