LPCTSTR转换为LPCSTR的方法

首先,在std::wstring的变量中
wstring st = _T(“sstt”);
转换为LPCTSTR: LPCTSTR ST = st.c_str(); 转换为 wstring: std::wstring AA = (LPCTSTR)ST;

在std::string中,
string mt = “MTMT”; 转换为LPCSTR的方式为 mt.c_str();

在我的使用过程中,由于要使用Winexec函数来打开指定路径下的.exe文件,要求传入LPCSTR类型的变量,然而程序中已有的变量只有LPCTSTR
当变量名path为wstring类型时,
编写 Winexec(path,SW_SHOWNORMAL);时 在Visual Studio中有以下提示

std::wstring CMW:m_oldPath
不存在从"stdwstring"到"LPCSTR”的适当转换函数

解决办法为:先定义一个string类型的变量,通过WideCharToMultiByte把数据传给string,再转换成LPCSTR即可,使用代码如下:

		wstring m_oldPath = _T("C:\\Users\AMB\\AppData\\Roaming\\abc"); 
		string result;
		//获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的  
		int len = WideCharToMultiByte(CP_ACP, 0, m_oldInsPath.c_str(), m_oldInsPath.size(), NULL, 0, NULL, NULL);
		char* buffer = new char[len + 1];
		//宽字节编码转换成多字节编码  
		WideCharToMultiByte(CP_ACP, 0, m_oldInsPath.c_str(), m_oldInsPath.size(), buffer, len, NULL, NULL);
		buffer[len] = '\0';
		//删除缓冲区并返回值  
		result.append(buffer);
		result = result + "\\" + APP_NAME + ".exe";
		delete[] buffer;
		LPCSTR oldpath = result.c_str();
		WinExec(oldpath, SW_SHOWNORMAL);
		Close();

参考来源:https://blog.csdn.net/liminwang0311/article/details/79975174
https://blog.csdn.net/qq_31603955/article/details/108481878

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值