Thursday 10 September 2009

Using Wide Charachters in C++

The normal 'char' is 8 bits. There is a 'wide char' (wchar_t) that is generally 16 bits. The width of wchar_t is compiler specific and can be as small as 8 bits. It is therefore recommended that it should not be used for creating portable programs.

A simple example as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of printing and comparing wide charachters
#include<iostream>

using namespace
std;

int
main()
{

wchar_t
wide_charachter;
wide_charachter = L'c';
//using wcout for printing
wcout<<"Wide Output of wide_charachter = "<<wide_charachter<<endl;

wstring wide_string; //wide string
wide_string = L"A wide string";
wcout<<"Wide Output of wide_string = "<<wide_string.c_str()<<endl;

wstring new_wide_string(L"Another wide string");

//comparing strings
if(wcscmp(new_wide_string.c_str(),wide_string.c_str())== 0)
cout<<"new_wide_string == wide_string"<<endl;
else

cout<<"new_wide_string != wide_string"<<endl;

if
(wcscmp(new_wide_string.c_str(),L"Another wide string")== 0)
cout<<"new_wide_string == L\"Another wide string\""<<endl;

return
0;
}




The output is as follows:

No comments:

Post a Comment