我希望你是我独家记忆

一段永远封存的记忆,随风而去
posts - 263, comments - 31, trackbacks - 0, articles - 3
   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理

string wstring 转换

Posted on 2009-10-10 13:47 Hero 阅读(935) 评论(0)  编辑 收藏 引用 所属分类: C++
 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std ;
 5 
14 
15 std::string ws2s(const std::wstring& ws)
16 {
17     std::string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";
18     setlocale(LC_ALL, "chs");
19     const wchar_t* _Source = ws.c_str();
20     size_t _Dsize = 2 * ws.size() + 1;
21     char *_Dest = new char[_Dsize];
22     memset(_Dest,0,_Dsize);
23     wcstombs(_Dest,_Source,_Dsize);
24     std::string result = _Dest;
25     delete []_Dest;
26     setlocale(LC_ALL, curLocale.c_str());
27     return result;
28 }
29 
30 std::wstring s2ws(const std::string& s)
31 {
32     setlocale(LC_ALL, "chs"); 
33     const char* _Source = s.c_str();
34     size_t _Dsize = s.size() + 1;
35     wchar_t *_Dest = new wchar_t[_Dsize];
36     wmemset(_Dest, 0, _Dsize);
37     mbstowcs(_Dest,_Source,_Dsize);
38     std::wstring result = _Dest;
39     delete []_Dest;
40     setlocale(LC_ALL, "C");
41     return result;
42 }
43 
44 int main()
45 {
46     freopen( "data.in""r", stdin ) ;
47     freopen( "data.out""w", stdout ) ;
48 
49     //wcout.imbue( locale("chs") ) ;
50     string line ;
51     wstring wline ;
52     wstring oline ;
53     VEC vec ;
54 
55     cout << sizeofchar ) << endl ;
56     cout << sizeof( wchar_t ) << endl ;
57 
58     while( cin >> line )
59     {
60         //cout << line << endl ;
61 
62         wline = s2ws( line ) ;
63 
64         cout << ws2s( wline ) << endl ;
65 
66         forint i=0; i<wline.length(); i++ )
67         {
68             oline += wline[i] ;
69             oline += (wchar_t)('/') ;
70         }
71 
72         cout << ws2s( oline ) << endl ;
73     }
74 
75     return 0 ;
76 }

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理