### C++ 数据类型转换详解
在C++编程中,数据类型转换是常见需求之一,尤其在涉及多种数据类型的处理场景下。本文将详细介绍C++中几种常见数据类型之间的转换方法,包括`string`、`CString`、`int`、`long`、`float`、`double`等类型之间的转换。
#### 1. `string`类型转换
**1.1 `string`到`CString`**
```cpp
std::string str = "Hello, World!";
CString cstr(str.c_str()); // 使用.c_str()将std::string转换为C风格字符串,然后传递给CString构造函数
```
**1.2 `string`到`char*`**
```cpp
std::string str = "Hello, World!";
const char* ch = str.c_str(); // 直接调用.c_str()方法
```
**1.3 `string`到`double`**
```cpp
std::string str = "123.45";
double dou = std::stod(str); // 使用stod函数
```
**1.4 `string`到`int`**
```cpp
std::string str = "123";
int i = std::stoi(str); // 使用stoi函数
```
#### 2. `CString`类型转换
**2.1 `CString`到`char*`**
```cpp
CString cstr = _T("Hello, World!");
char* ch = nullptr;
// 不出现乱码
ch = cstr.GetBuffer(0);
// 出现乱码,还需将wchar_t*转为char*
ch = toNarrowString(cstr.GetBuffer(0));
```
**2.2 `CString`到`std::string`**
```cpp
CString cstr = _T("Hello, World!");
std::string str = CStringA(cstr); // 使用CStringA进行转换
```
**2.3 `CString`到`int`**
```cpp
CString cstr = _T("123");
int i = 0;
cstr >> i; // 使用运算符重载进行转换
```
**2.4 `CString`格式化**
```cpp
CString cstr;
int temp = 123;
float fTemp = 123.45;
// %d 转 int
cstr.Format(_T("%d"), temp);
// %f 转 float/double
cstr.Format(_T("%f"), fTemp);
// %s 转 string
cstr.Format(_T("%s"), "Hello, World!");
```
#### 3. `char*`类型转换
**3.1 `char*`到`std::string`**
```cpp
const char* ch = "Hello, World!";
std::string str(ch); // 直接构造
```
**3.2 `char*`到`CString`**
```cpp
const char* ch = "Hello, World!";
CString cstr(ch); // 使用构造函数直接转换
```
**3.3 `char*`到`wchar_t*`**
```cpp
const char* pStr = "Hello, World!";
// 转换宽字符的处理
wchar_t* toWideString(const char* pStr) {
setlocale(LC_ALL, ".936"); // 获取双字节的个数
size_t nChars = mbstowcs(nullptr, pStr, 0);
if (nChars == 0) return L"";
wchar_t* buff = new wchar_t[nChars + 1];
mbstowcs(buff, pStr, nChars + 1);
buff[nChars] = 0;
setlocale(LC_ALL, "C");
return buff;
}
std::wstring toWideString(const std::string& str) {
if (str.empty()) {
return L"";
}
wchar_t* wcRet = toWideString(str.c_str());
std::wstring ret(wcRet);
delete[] wcRet;
return ret;
}
```
#### 4. `wchar_t*`类型转换
**4.1 `wchar_t*`到`char*`**
```cpp
const wchar_t* pStr = L"Hello, World!";
// 转窄字符的处理
char* toNarrowString(const wchar_t* pStr) {
setlocale(LC_ALL, ".936"); // 获取双字节的个数
int nChars = wcstombs(nullptr, pStr, 0);
if (nChars == 0) return "";
char* buff = new char[nChars + 1];
wcstombs(buff, pStr, nChars + 1);
buff[nChars] = 0;
setlocale(LC_ALL, "C");
return buff;
}
std::string toNarrowString(const std::wstring& str) {
if (str.empty()) {
return "";
}
char* cRet = toNarrowString(str.c_str());
std::string ret(cRet);
delete[] cRet;
return ret;
}
```
以上介绍了C++中常见的数据类型转换方法,包括了`std::string`、`CString`、`char*`和`wchar_t*`等之间的转换。掌握这些转换技巧有助于提高程序的可读性和可维护性。需要注意的是,在实际开发中应根据具体情况选择合适的方法,并注意数据安全问题,避免因不当转换导致的程序错误或安全隐患。