2013年5月1日 星期三

string 和 wstring 互相轉換,適用於ASCII編碼

#include < iostream >
#include < string >
using namespace std;
int main(void)
{
 // -----------------------------------------------------------------
 // 1. string to wstring
 // -----------------------------------------------------------------
 // 不適用其他非ASCII編碼(1 byte)的字元,如Unicode編碼(2 bytes)之中文
 string str1 = "abc";

 wstring wstr1;
 wstr1.assign(str1.begin(), str1.end());
 // or
 // wstring wstr1(str1.begin(), str1.end());
 wcout << wstr1 << endl;
 // -----------------------------------------------------------------
 // 2. wstring to string
 // -----------------------------------------------------------------
 wstring  wstr2 = L"abc";
 string str2(wstr2.begin(), wstr2.end());
 // or
 //str2.assign(wstr2.begin(), wstr2.end());
 cout << str2 << endl;
}

沒有留言:

張貼留言