String 转lpcstr
时间: 2024-01-12 07:22:37 浏览: 117
const char*转LPCWSTR 字符串转换
5星 · 资源好评率100%
以下是两种将String转换为LPCSTR的方法:
1. 使用c_str()函数:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "abcd";
LPCSTR str1 = str.c_str();
std::cout << "LPCSTR: " << str1 << std::endl;
return 0;
}
```
2. 使用MultiByteToWideChar函数进行转换:
```cpp
#include <iostream>
#include <string>
#include <Windows.h>
LPCWSTR str2LPCWSTR(std::string str) {
int len = str.length();
int lenbf = MultiByteToWideChar(CP_ACP, 0, str.c_str(), len, 0, 0);
wchar_t* buffer = new wchar_t[lenbf];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), len, buffer, sizeof(wchar_t) * lenbf);
buffer[len] = 0;
return buffer;
}
int main() {
std::string str = "abcd";
LPCWSTR str1 = str2LPCWSTR(str);
std::wcout << "LPCWSTR: " << str1 << std::endl;
delete[] str1;
return 0;
}
```
阅读全文