2009年2月27日星期五

怎样转换各种String 类型

How to: Convert Between Various String Types
这是MSDN中的内容,在各种不同的string类型间转换,包括System::String和标准C++中的std::string间的转换。
This topic demonstrates how to convert various Visual C++ string types into other strings. The strings types that are covered include char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System..::.String. In all cases, a copy of the string is made when converted to the new type. Any changes made to the new string will not affect the original string, and vice versa.

// 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, _TRUNCATE);
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;
}

没有评论: