// convert_from_basic_string.cpp
// compile with: /clr /link comsuppw.lib
#include <iostream>
#include <stdlib.h>
#include <string>
#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*
// You 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(), _TRUNCATE);
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;
}
如何从 basic_string 转换为其他字符串类型
最新推荐文章于 2023-05-25 15:03:13 发布