在C++中有很多的数据类型,在编程的时候,对数据类型进行转换很常遇到的,我在编程过程中频繁遇到甚至头疼,于是在网上网罗各种方法帖子。因为时间有限没法一一整理,遂将各帖汇集一处,与大家共享。希望对大家有帮助。
为方便大家区分各帖。每个帖的首页都是另起一页,不会直接跟在后一个帖后面。
1、如何将CString变量转换为int变量
2、如何将int变量转换CString为变量
CString ss="1212.12";
int temp=atoi(ss);
CString aa;
aa.Form at("%d",temp);
3、CString转换为Double
4、Double转换为CString
CString strValue("1.234");
double dblValue;
dblValue = atof((LPCTSTR)strValue);
5、char*转换成CString
若将char*转换成CString,除了直接赋值外,还可使用CString::Format进行。例如:char chArray[] = "This is a test";
char * p = "This is a test";
或
LPSTR p = "This is a test";
或在已定义Unicode应的用程序中
TCHAR * p = _T("This is a test");
或
LPTSTR p = _T("This is a test");
CString theString = chArray;
theString.Format(_T("%s"), chArray);
theString = p;
6、CString转换成char*
若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:
方法一,使用强制转换。例如:
CString theString( "This is a test" );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
方法二,使用strcpy。例如:
CString theString( "This is a test" );
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);
需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const w char_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。
方法三,使用CString::GetBuffer。例如:
CString s(_T("This is a test "));
LPTSTR p = s.GetBuffer();
// 在这里添加使用p的代码
if(p != NULL) *p = _T('\0');
s.ReleaseBuffer();
// 使用完后及时释放,以便能使用其它的CString成员函数
7、BST R转换成char*
方法一,使用ConvertBST RToString。例如:
#include
#pragma comment(lib, "com supp.lib")
int _t m ain(int argc, _TCHAR* argv[]){
BST R bstrText = ::SysAllocString(L"Test");
char* lpszText2 = _com_util::ConvertBST RToString(bstrText);
SysFreeString(bstrText); // 用完释放
delete[] lpszText2;
return 0;
}
方法二,使用_bstr_t的赋值运算符重载。例如:
_bstr_t b = bstrText;
char* lpszText2 = b;
8、char*转换成BST R
方法一,使用SysAllocString等API函数。例如:
BST R bstrText = ::SysAllocString(L"Test");
BST R bstrText = ::SysAllocStringLen(L"Test",4);
BST R bstrText = ::SysAllocStringByteLen("Test",4);
方法二,使用COleVariant或_variant_t。例如:
//COleVariant strVar("This is a test");
_variant_t strVar("This is a test");
BST R bstrText = strVar.bstrVal;
方法三,使用_bstr_t,这是一种最简单的方法。例如:
BST R bstrText = _bstr_t("This is a test");
方法四,使用CComBST R。例如:
BST R bstrText = CComBST R("This is a test");
或
CComBSTR bstr("This is a test");
BST R bstrText = bstr.m_str;
方法五,使用ConvertStringToBSTR。例如:
char* lpszText = "Test";
BST R bstrText = _com_util::ConvertStringToBST R(lpszText);
9、CString转换成BSTR
通常是通过使用CStringT::AllocSysString来实现。例如:
CString str("This is a test");
BST R bstrText = str.AllocSysString();
…
SysFreeString(bstrText); // 用完释放
10、BSTR转换成CString
一般可按下列方法进行:
BST R bstrText = ::SysAllocString(L"Test");
CStringA str;
str.Em pty();
str = bstrText;
或
CStringA str(bstrText);
11、ANSI、Unicode和宽字符之间的转换
方法一,使用MultiByteToWideChar将ANSI字符转换成Unicode字符,使用Wide CharToMultiByte将Unicode字符转换成ANSI字符。
方法二,使用“_T”将ANSI转换成“一般”类型字符串,使用“L”将ANSI转换成Unicode,而在托管C++环境中还可使用S将ANSI字符串转换成String*对象。例如:
TCHAR tstr[] = _T("this is a test");
wchar_t wszStr[] = L"This is a test";
String* str =S”This is a test”;
方法三,使用ATL 7.0的转换宏和类。ATL7.0在原有3.0基础上完善和增加了许多字符串转换宏以及提供相应的类,它具有如图3所示的统一形式:
其中,第一个C表示“类”,以便于ATL 3.0宏相区别,第二个C表示常量,2表示“to”,EX表示要开辟一定大小的缓冲。SourceType和DestinationType可以是A、T、W和OLE,其含义分别是ANSI、Unicode、“一般”类型和OLE字符串。例如,CA2CT就是将ANSI转换成一般类型的字符串常量。下面是一些示例代码:
LPTSTR tstr= CA2TEX<16>("this is a test");
LPCTSTR tcstr= CA2CT("this is a test");
wchar_t wszStr[] = L"This is a test";
char* chstr = CW2A(wszStr);
Visual C++ 如何:在各种字符串类型之间进行转换
本主题演示如何将各种C++ 字符串类型转换为其他字符串。可以转换的字符串类型包括char *、wchar_t*、_bstr_t、CComBSTR、CString、basic_string 和System.String。在所有情况下,在将字符串转换为新类型时,都会创建字符串的副本。对新字符串进行的任何更改都不会影响原始字符串,反之亦然。
从char * 转换
示例
说明
此示例演示如何从char * 转换为上面列出的其他字符串类型。
// convert_from_char.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;
// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCA TE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a CString
CString cstring(orig);
cstring += " (CString)";
cout << cstring << endl;
// Convert to a basic_string
string basicstring(orig);
basicstring += " (basic_string)";
cout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)
从wchar_t * 转换
示例
说明
此示例演示如何从wchar_t * 转换为上面列出的其他字符串类型。// convert_from_wchar_t.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
wchar_t *orig = L"Hello, World!";
wcout << orig << L" (wchar_t *)" << endl;
// Convert to a char*
size_t origsize = wcslen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
char nstring[newsize];
wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCA TE);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a CString
CString cstring(orig);
cstring += " (CString)";
cout << cstring << endl;
// Convert to a basic_string
wstring basicstring(orig);
basicstring += L" (basic_string)";
wcout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (wchar_t *)
Hello, World! (char *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)
从_bstr_t 转换
示例
说明
此示例演示如何从_bstr_t 转换为上面列出的其他字符串类型。// convert_from_bstr_t.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
_bstr_t orig("Hello, World!");
wcout << orig << " (_bstr_t)" << endl;
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, (char *)orig);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, (wchar_t *)orig);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a CComBSTR
CComBSTR ccombstr((char *)orig);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a CString
CString cstring((char *)orig);
cstring += " (CString)";
cout << cstring << endl;
// Convert to a basic_string
string basicstring((char *)orig);
basicstring += " (basic_string)";
cout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String((char *)orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (_bstr_t)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)
从CComBSTR 转换
示例
说明
此示例演示如何从CComBSTR 转换为上面列出的其他字符串类型。// convert_from_ccombstr.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "vcclr.h"
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
int main()
{
CComBSTR orig("Hello, World!");
CW2A printstr(orig);
cout << printstr << " (CComBSTR)" << endl;
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
CW2A tmpstr1(orig);
strcpy_s(nstring, tmpstr1);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, orig);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CString
CString cstring(orig);
cstring += " (CString)";
cout << cstring << endl;
// Convert to a basic_string
wstring basicstring(orig);
basicstring += L" (basic_string)";
wcout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (CComBSTR)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)
从CString 转换
示例
说明
此示例演示如何从CString 转换为上面列出的其他字符串类型。// convert_from_cstring.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
CString orig("Hello, World!");
wcout << orig << " (CString)" << endl;
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
// Y ou must first convert to a char * for this to work.
size_t origsize = strlen(orig) + 1;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCA TE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a basic_string
string basicstring(orig);
basicstring += " (basic_string)";
cout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (CString)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (basic_string)
Hello, World! (System::String)
从basic_string 转换
示例
说明
此示例演示如何从basic_string 转换为上面列出的其他字符串类型。
// convert_from_basic_string.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
string orig("Hello, World!");
cout << orig << " (basic_string)" << endl;
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig.c_str());
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
// Y ou must first convert to a char * for this to work.
size_t origsize = strlen(orig.c_str()) + 1;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCA TE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig.c_str());
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(orig.c_str());
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a CString
CString cstring(orig.c_str());
cstring += " (CString)";
cout << cstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig.c_str());
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
输出
Hello, World! (basic_string)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (System::String)
从System::String 转换
示例
说明
此示例演示如何从System.String 转换为上面列出的其他字符串类型。// convert_from_system_string.cpp
// compile with /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "vcclr.h"
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
int main()
{
String ^orig = gcnew String("Hello, World!");
Console::WriteLine("{0} (System::String)", orig);
pin_ptr
// Convert to a char*
size_t origsize = wcslen(wch) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
char nstring[newsize];
wcstombs_s(&convertedChars, nstring, origsize, wch, _TRUNCA TE);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, wch);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(wch);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(wch);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a CString
CString cstring(wch);
cstring += " (CString)";
cout << cstring << endl;
// Convert to a basic_string
wstring basicstring(wch);
basicstring += L" (basic_string)";
wcout << basicstring << endl;
delete orig;
}
输出
通过阅读本文你可以学习如何有效地使用CString
CString 是一种很有用的数据类型。它们很大程度上简化了MFC中的许多操作,使得MFC在做字符串操作的时候方便了很多。不管怎样,使用CString有很多特殊的技巧,特别是对于纯C背景下走出来的程序员来说有点难以学习。这篇文章就来讨论这些技巧。
使用CString可以让你对字符串的操作更加直截了当。这篇文章不是CString的完全手册,但囊括了大部分常见基本问题。
这篇文章包括以下内容:
CString 对象的连接
格式化字符串(包括int 型转化为CString )
CString 型转化成int 型
CString 型和char* 类型的相互转化
char* 转化成CString
CString 转化成char* 之一:使用LPCTSTR强制转化
CString 转化成char* 之二:使用CString对象的GetBuffer方法
CString 转化成char* 之三: 和控件的接口
CString 型转化成BSTR 型;
BSTR 型转化成CString 型;
V ARIANT 型转化成CString 型;
载入字符串表资源;
CString 和临时对象;
CString 的效率;
总结
下面我分别讨论。
1、CString 对象的连接
能体现出CString 类型方便性特点的一个方面就字符串的连接,使用CString 类型,你能很方便地连接两个字符串,正如下面的例子:
CString gray("Gray");
CString cat("Cat");
CString graycat = gray + cat;
要比用下面的方法好得多:
char gray[] = "Gray";
char cat[] = "Cat";
char * graycat = malloc(strlen(gray) + strlen(cat) + 1);
strcpy(graycat, gray);
strcat(graycat, cat);
2、格式化字符串
与其用sprintf() 函数或wsprintf() 函数来格式化一个字符串,还不如用CString 对象的Format()方法:
CString s;
s.Format(_T("The total is %d"), total);
用这种方法的好处是你不用担心用来存放格式化后数据的缓冲区是否足够大,这些工作由CString类替你完成。
格式化是一种把其它不是字符串类型的数据转化为CString类型的最常用技巧,比如,把一个整数转化成CString类型,可用如下方法:
CString s;
s.Format(_T("%d"), total);
我总是对我的字符串使用_T()宏,这是为了让我的代码至少有Unicode的意识,当然,关于Unicode的话题不在这篇文章的讨论范围。_T()宏在8位字符环境下是如下定义的:
#define _T(x) x // 非Unicode版本(non-Unicode version)
而在Unicode环境下是如下定义的:
#define _T(x) L##x // Unicode版本(Unicode version)
所以在Unicode环境下,它的效果就相当于:
s.Format(L"%d", total);
如果你认为你的程序可能在Unicode的环境下运行,那么开始在意用Unicode 编码。比如说,不要用sizeof() 操作符来获得字符串的长度,因为在Unicode环境下就会有2倍的误差。我们可以用一些方法来隐藏Unicode的一些细节,比如在我需要获得字符长度的时候,我会用一个叫做DIM的宏,这个宏是在我的dim.h文件中定义的,我会在我写的所有程序中都包含这个文件:
#define DIM(x) ( sizeof((x)) / sizeof((x)[0]) )
这个宏不仅可以用来解决Unicode的字符串长度的问题,也可以用在编译时定义的表格上,它可以获得表格的项数,如下:
class Whatever { ... };
Whatever data[] = {
{ ... },
...
{ ... },
};
for(int i = 0; i < DIM(data); i++) // 扫描表格寻找匹配项。
这里要提醒你的就是一定要注意那些在参数中需要真实字节数的API函数调用,如果你传递字符个数给它,它将不能正常工作。如下:TCHAR data[20];
lstrcpyn(data, longstring, sizeof(data) - 1); // WRONG!
lstrcpyn(data, longstring, DIM(data) - 1); // RIGHT
WriteFile(f, data, DIM(data), &bytesWritten, NULL); // WRONG!
WriteFile(f, data, sizeof(data), &bytesWritten, NULL); // RIGHT
造成以上原因是因为lstrcpyn需要一个字符个数作为参数,但是WriteFile却需要字节数作为参数。
同样需要注意的是有时候需要写出数据的所有内容。如果你仅仅只想写出数据的真实长度,你可能会认为你应该这样做:
WriteFile(f, data, lstrlen(data), &bytesWritten, NULL); // WRONG
但是在Unicode环境下,它不会正常工作。正确的做法应该是这样:
WriteFile(f, data, lstrlen(data) * sizeof(TCHAR), &bytesWritten, NULL); // RIGHT 因为WriteFile需要的是一个以字节为单位的长度。(可能有些人会想“在非Unicode的环境下运行这行代码,就意味着总是在做一个多余的乘1操作,这样不会降低程序的效率吗?”这种想法是多余的,你必须要了解编译器实际上做了什么,没有哪一个C或C++编译器会把这种无聊的乘1操作留在代码中。在Unicode环境下运行的时候,你也不必担心那个乘2操作会降低程序的效率,记住,这只是一个左移一位的操作而已,编译器也很乐意为你做这种替换。)
使用_T宏并不是意味着你已经创建了一个Unicode的程序,你只是创建了一个有Unicode意识的程序而已。如果你在默认的8-bit模式下编译你的程序的话,得到的将是一个普通的8-bit的应用程序(这里的8-bit指的只是8位的字符编码,并不是指8位的计算机系统);当你在Unicode环境下编译你的程序时,你才会得到一个Unicode的程序。记住,CString 在Unicode 环境下,里面包含的可都是16位的字符哦。
3、CString 型转化成int 型
把CString 类型的数据转化成整数类型最简单的方法就是使用标准的字符串到整数转换例程。
虽然通常你怀疑使用_atoi()函数是一个好的选择,它也很少会是一个正确的选择。如果你准备使用Unicode 字符,你应该用_ttoi(),它在ANSI 编码系统中被编译成_atoi(),而在Unicode 编码系统中编译成_wtoi()。你也可以考虑使用_tcstoul()或者_tcstol(),它们都能把字符串转化成任意进制的长整数(如二进制、八进制、十进制或十六进制),不同点在于前者转化后的数据是无符号的(unsigned),而后者相反。看下面的例子:
CString hex = _T("FAB");
CString decimal = _T("4011");
ASSERT(_tcstoul(hex, 0, 16) == _ttoi(decimal));
4、CString 型和char* 类型的相互转化
这是初学者使用CString 时最常见的问题。有了C++ 的帮助,很多问题你不需要深入的去考虑它,直接拿来用就行了,但是如果你不能深入了解它的运行机制,又会有很多问题让你迷惑,特别是有些看起来没有问题的代码,却偏偏不能正常工作。
比如,你会奇怪为什么不能写向下面这样的代码呢: