Thursday 17 September 2009

Converting normal string/char to wide string/char and vice versa

When you are playing with wide charachters in C++, you sometimes need to covert it into normal charachters and vice versa. Here is a simple program that I picked up from somewhere but cant remember.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to convert from Wide to Narrow strings and Vice Versa
#include<iostream>
#include <sstream>

using namespace
std;

wstring widen( const string& str)
{

wostringstream wstm ;
const
ctype<wchar_t>& ctfacet = use_facet< ctype<wchar_t> >( wstm.getloc() ) ;
for
( size_t i=0 ; i<str.size() ; ++i )
wstm << ctfacet.widen( str[i] ) ;
return
wstm.str() ;
}


string narrow( const wstring& str )
{

ostringstream stm ;
const
ctype<char>& ctfacet = use_facet< ctype<char> >( stm.getloc() ) ;
for
( size_t i=0 ; i<str.size() ; ++i )
stm << ctfacet.narrow( str[i], 0 ) ;
return
stm.str() ;}

int
main()
{
{

const
wchar_t* wcstr = L"asdfg12345" ;
string cstr = narrow(wcstr);
cout <<"\nOutput from wide to narrow = "<< cstr.c_str() << endl ;
}
{

const
char* cstr = "zxcvb67890" ;
wstring wcstr = widen(cstr);
wcout << L"\nOutput from narrow to wide = "<<wcstr.c_str() << endl ;
}

return
0;
}






The output is as follows:


No comments:

Post a Comment