首先,在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