string?

摘要:關於string wstring _bstr_t的互相轉換的深入研究。

string wstring _bstr_t的互相轉換

步驟/方法

今天在研究VC++ 使用 ADO 讀取MS SQKSERVER 資料庫時, 發現:
string ansi字串
wstring unicode字串
_bstr_t com字串

之間的轉換關係,示例如下:
// ex_02_wstring_cv_string.cpp : 定義控制檯應用程式的入口點。
//
#include "stdafx.h"
#include "string"
#include "icrsint.h"
#include "comutil.h"

using namespace std;
#import "C:\\Program Files\\Common Files\\System\\ADO\\msado15.dll" no_namespace rename("EOF", "EndOfFile")
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
wstring ws1,ws2;

ws2 = L"春如舊,人空瘦,淚痕紅浥鮫綃透。桃花落,閒池閣,山盟雖在,錦書難託。莫、莫、莫。";
// 從 unicode 字串轉化為 ansi字串
string s = (char *) _bstr_t ( ws2.c_str() );
// 從 ansi字串轉化為 unicode 字串
ws1 = ( wchar_t *) ( _bstr_t ( s.c_str( ) ));
setlocale(LC_ALL, "chs");
wprintf( L"原wstring串=%s\n",ws2.c_str());
printf( "轉換為string串=%s\n", s.c_str());
wprintf( L"轉換為wstring串=%s\n",ws1.c_str());
::CoUninitialize();
getchar();
return 0;
}

--- 結果 ---
原wstring串=春如舊,人空瘦,淚痕紅浥鮫綃透。桃花落,閒池閣,山盟雖在,錦書難託。莫、莫、莫。
轉換為string串=春如舊,人空瘦,淚痕紅浥鮫綃透。桃花落,閒池閣,山盟雖在,錦書難託。莫、莫、莫。
轉換為wstring串=春如舊,人空瘦,淚痕紅浥鮫綃透。桃花落,閒池閣,山盟雖在,錦書難託。莫、莫、莫。

摘要, 深入研究,
相關問題答案