std::string 转Cstring
时间: 2023-11-14 15:05:12 浏览: 32
可以使用 `c_str()` 函数将 `std::string` 转换为 C 风格的字符串,例如:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
const char* cstr = str.c_str();
std::cout << cstr << std::endl;
return 0;
}
```
输出:
```
Hello, world!
```
注意:`c_str()` 返回的是一个指向内部字符数组的常量指针,因此不要修改这个指针所指向的字符数组。
相关问题
std::string转CString
要将std::string转换为CString,可以使用c_str()函数。它将std::string对象转换为以null结尾的C字符串。以下是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
const char* cstr = str.c_str();
std::cout << "std::string: " << str << std::endl;
std::cout << "CString: " << cstr << std::endl;
return 0;
}
```
在上面的示例中,我们调用std::string的c_str()函数将字符串转换为CString,并将其赋值给一个const char*变量cstr。然后,我们可以使用这个CString进行后续的操作。注意,由于c_str()返回的是指向内部缓冲区的指针,确保在使用cstr之前不要修改原始std::string对象的内容。
std::string 转cString
可以使用Unicode将std::string字符串转换为CString字符串。具体实现方法可以参考以下代码:
```
CString CMyApp::TranslatestringToCStringByUnicode(IN const string& strSource) {
CString strResult = _T("");
strResult = strSource.c_str();
return strResult;
}
```
其中,strSource为需要转换的std::string字符串,strResult为转换后的CString字符串。
另外,如果需要将CString字符串转换为std::string字符串,也可以使用以下代码实现:
```
string CMyApp::TranslateCStringTostringByUnicode(IN CString& strSource) {
int nSourceLen = strSource.GetLength();
int nSourceBytes = WideCharToMultiByte(CP_ACP, 0, strSource, nSourceLen, NULL, 0, NULL, NULL);
char* chrTemp = new char[nSourceBytes + 1];
memset(chrTemp, 0, nSourceBytes + 1);
WideCharToMultiByte(CP_OEMCP, 0, strSource, nSourceLen, chrTemp, nSourceBytes, NULL, NULL);
chrTemp[nSourceBytes] = 0;
std::string strResult = chrTemp;
delete[] chrTemp;
return strResult;
}
```