Wednesday, 23 December 2009

Example of SetEnvironmentVariable and GetEnvironmentVariable

Sometimes you may want to communicate between different DLL's using some sort of flags. The simplest way to do it probably is using environment variable. Here is a simple example but can be modified to suit multiple DLL's.





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<atlstr.h>

using namespace
std;

int
main()
{

//Suppose we want to have a temporary environment variable called "ZahidVar" whose value could be "120" or "140"
string varName("ZahidVar");
CString value;
DWORD len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();

if
(len)
cout<<"Value of environment variable = "<<value<<endl;
else

cout<<"environment variable was empty"<<endl;

//Set the environment variable now
SetEnvironmentVariable("ZahidVar", "120");

len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();

if
(len)
cout<<"Value of environment variable = "<<value<<endl;
else

cout<<"environment variable was empty"<<endl;

return
0;
}







The output is as follows:


It should be noted that the scope of this environment variable is temporary and will cease to exist once the program exits.

You can also look at this example to show you how to print all the environment variables.

Wednesday, 16 December 2009

BOOL to bool

I faced a very simple problem the other day. The compiler started generating a warning:

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

The reason being that because I was including some Windows file that included windef.h. In windef.h, it says: typedef int BOOL;

What I was trying to do was to cast that BOOL to bool. Of course we can suppress the warning easily by the #pragma directives as discussed earlier but there has to be a better and a simpler way. Then it clicked, how about a simple != 0 comparison. Here is the sample code:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<windows.h>
#include<windef.h>

using namespace
std;

int
main()
{

BOOL someVal = 1;

bool
firstApproach = someVal; //Generates warning C4800
cout<<"firstApproach = "<<firstApproach<<endl;

bool
secondApproach = (someVal != 0); //No Warning
cout<<"secondApproach = "<<secondApproach<<endl;

return
0;
}

Wednesday, 9 December 2009

Catching the 'Divide By Zero' exceptions

I was surprised to find that C++ does not catch divide by 0 exceptions by default. The code will crash when a divide by 0 situation occurs. As a result the only option is to write our own class or method to handle divide by 0 scenario. The example below shows how to handle the Divide by zero scenario and how to construct an exception.







//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Division
{

public
:
double
quotient(int numerator, int denominator);
private
:

};


double
Division::quotient(int numerator, int denominator)
{

if
(!denominator)
{

exception e("Divide by 0 exception");
throw
(e);
}

return
(static_cast< double >( numerator ))/denominator;
}



int
main()
{

Division d;
try

{

cout<<"1. (100/10) = "<<d.quotient(100, 10)<<endl;
cout<<"2. (10/4) = "<<d.quotient(10, 4)<<endl;
cout<<"3. (10/0) = "<<d.quotient(10, 0)<<endl;
cout<<"4. (30/9) = "<<d.quotient(30, 9)<<endl;
}

catch
(exception& e)
{

cout<<"Exception caught with cause :"<<e.what()<<endl;
}

return
0;
}








The output is as follows:


You can read more on this topic here.

Wednesday, 2 December 2009

Using constants with functions

There always seems to be confusion in using const with functions. I am not referring to const functions that have const after the function name, that is straightforward. Also, the way functions behave when you have const before them is different than the built-in types. I have earlier provided a table for that.

Here is a simple program that shows different types of const with functions.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

class
A
{

public
:
int
x;
};


class
B
{

public
:
string y;
};


A* const createA()
{

return
(new A);
}


const
B* createB()
{

return
(new B);
}


int
main()
{

A* a = NULL;
a = createA();
a->x = 100;
cout<<"a.x = "<<a->x<<endl;
delete
a;

const
B* b = NULL;
b = createB();
//b->y = "Hello"; - Compilation error because b is constant
(const_cast<B*>(b))->y = "Hello";
cout<<"b.y = "<<b->y<<endl;
delete
b;

A* const a2 = NULL;
//a2 = createA(); - Compilation Error:
// you cannot assign to a variable that is const

A* const a3 = new A; //not possible to change what a3 points to now
a3->x = 23456;
cout<<"a3.x = "<<a3->x<<endl;
delete
a3;

return
0;
}






The output is as follows:

Wednesday, 25 November 2009

Input/Output with files

The following is a simple program to show reading, writing and appending to files. You can read more about this feature at cplusplus.com.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <fstream>
#include <string>

using namespace
std;

int
main()
{

string line;
cout<<"\nFile 1 operations - Writing to Hello.txt"<<endl;
ofstream file1; //OUTPUT file Stream
file1.open("Hello.txt"); //Open the file
file1 << "Writing something something to a file"<<endl;
file1 << "This is enough for the time being"<<endl;

if
(file1.is_open()) //Check if open
{
/*
while (!file1.eof())
{
getline (file1,line); - NOT POSSIBLE because of ofstream
cout << line << endl;
}
*/

}

file1.close(); //Close file1

cout<<"\nFile 2 operations - Reading from Hello.txt"<<endl;
ifstream file2; //INPUT file stream
file2.open("Hello.txt"); //Open the file
if(file2.is_open()) //Check if open
{
while
(!file2.eof())
{

getline (file2,line);
cout << line << endl;
}
}

file2.close(); //Close file2


cout<<"\nFile 3 operations - Appending and Reading from Hello.txt"<<endl;
fstream file3; //INPUT file stream
file3.open("Hello.txt", ios::in | ios::out); //Open the file
if(file3.is_open()) //Check if open
{
//We want to put a new line at the end of the file
file3.seekp(0, ios::end);
file3 << "This is new line added file 3"<<endl;
//Now reset the file pointer to the start of the file
file3.seekg(0, ios::beg);
while
(!file3.eof())
{

getline (file3,line);
cout << line << endl;
}
}

file3.close(); //Close file3

return
0;
}








The output is as follows:

Monday, 16 November 2009

C String and C++ Strings: Similarities and Differences

I came across this scenario recently when a C style string (as some people refer to char[] as) had to be compared to a C++ string and even though this is straightforward, i fell in the same trap as a lot of people about forgetting that there is a Nul charachter as the end of C style string. Anyway, here is an example to demonstrate both the strings.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate length and size of char* and string
//and to show similarity and difference between them
#include<iostream>

using namespace
std;

int
main()
{

cout<<endl;
char
a[10]="Hello";
cout<<"Size of a = "<<sizeof(a)<<endl;
a[5]='\0'; //Terminating the C string in between with Nul character
cout<<"Size of a = "<<sizeof(a)<<endl;

cout<<endl;
char
b[]="Hello";
cout<<"Size of b = "<<sizeof(b)<<endl; //Note the size
//Automatic Nul charachter added

cout<<endl;
string c("Hello");
cout<<"Size of c = "<<sizeof(c)<<endl;
cout<<"Length of c = "<<c.length()<<endl;

c += " Zahid";
cout<<"Size of modified c = "<<sizeof(c)<<endl;
cout<<"Length of modified c = "<<c.length()<<endl;

//Add an extra NULL charachter
cout<<endl;
char
d[]="Hello\0";
cout<<"Size of d = "<<sizeof(d)<<endl;
for
(int i = 0; i < sizeof(d); i++)
{

cout<<"d["<<i<<"] = "<<d[i]<<endl;
}


//When is a char[] similar to string?
cout<<endl;
char
e[]="Zahid";
string f = "Zahid\0";
const
char* temp = f.c_str();
if
(strcmp(e , temp) == 0)
{

cout<<"e == f"<<endl;
}

else

{

cout<<"e != f"<<endl;
}


return
0;
}







The output is as follows:

Tuesday, 3 November 2009

Creating specialised strings using 'find_first_not_of'

Sometimes we want to create specialised strings that have a particular characteristic. For example a BitString that can only contain '0' and '1'. Or we may want to create a Hex String that can contain '0-9' and 'a-f'. We can also define other specialised types like numeric strings, octal strings, etc. The main thing would be to check to make sure that the string only contains valid characters. We can do this basic check using find_first_not_of function.

Here is a simple program to show its use:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to test specialised strings

#include <iostream>
#include <string>

using namespace
std;

bool
checkIfBitString(string testString)
{

return
(testString.find_first_not_of("01?") == std::string::npos);
}


bool
checkIfHexString(string testString)
{

return
(testString.find_first_not_of("0123456789aAbBcCdDeEfF?") == std::string::npos);
}


int
main()
{

cout<<endl;
string str1("010011000111010101");

if
(checkIfBitString(str1))
cout<<"str1 is a BitString"<<endl;
else

cout<<"str1 is not a BitString"<<endl;

if
(checkIfHexString(str1))
cout<<"str1 can also be a HexString"<<endl;
else

cout<<"str1 is not a HexString"<<endl;

cout<<endl;
string str2("010aBcDeF345678010101");

if
(checkIfBitString(str2))
cout<<"str2 is a BitString"<<endl;
else

cout<<"str2 is not a BitString"<<endl;

if
(checkIfHexString(str2))
cout<<"str2 is a HexString"<<endl;
else

cout<<"str2 is not a HexString"<<endl;

cout<<endl;
string str3("Banana");

if
(checkIfBitString(str3))
cout<<"str3 is a BitString"<<endl;
else

cout<<"str3 is not a BitString"<<endl;

if
(checkIfHexString(str3))
cout<<"str3 is a HexString"<<endl;
else

cout<<"str3 is not a HexString"<<endl;

return
0;
}






The output is as follows:

Wednesday, 21 October 2009

The challenging 'Infinite loop' problem

Picked this one up from The C++ blog.

Consider the following program:



#include <iostream>

int
main()
{

int
i;
int
array[4];
for
(i=0; i<=8; i++)
{

array[i]=0;
}


return
0;
}


Most people including myself expect this program to crash. This is not the case. The reason being the way everything is stored on stack. In simple representation, the storage is something like this:



So when i = 6, value of i is reset to 0 and the loop continues forever.

After digging some information on stack, heap, etc. I found some useful info in C++ in 24 hours:

Programmers generally deal with five areas of memory:
  • Global name space
  • The free store (a.k.a. Heap)
  • Registers
  • Code space
  • The stack

Local variables are on the stack, along with function parameters. Code is in code space, of course, and global variables are in global name space. The registers are used for internal housekeeping functions, such as keeping track of the top of the stack and the instruction pointer. Just about all remaining memory is given over to the free store, which is sometimes referred to as the heap.

The problem with local variables is that they don't persist. When the function returns, the local variables are thrown away. Global variables solve that problem at the cost of unrestricted access throughout the program, which leads to the creation of code that is difficult to understand and maintain. Putting data in the free store solves both of these problems.

You can think of the free store as a massive section of memory in which thousands of sequentially numbered cubbyholes lie waiting for your data. You can't label these cubbyholes, though, as you can with the stack. You must ask for the address of the cubbyhole that you reserve and then stash that address away in a pointer.

The stack is cleaned automatically when a function returns. All the local variables go out of scope, and they are removed from the stack. The free store is not cleaned until your program ends, and it is your responsibility to free any memory that you've reserved when you are done with it.

The advantage to the free store is that the memory you reserve remains available until you explicitly free it. If you reserve memory on the free store while in a function, the memory is still available when the function returns.

The advantage of accessing memory in this way, rather than using global variables, is that only functions with access to the pointer have access to the data. This provides a tightly controlled interface to that data, and it eliminates the problem of one function changing that data in unexpected and unanticipated ways.

For this to work, you must be able to create a pointer to an area on the free store and to pass that pointer among functions. The pointer is created using new and once you are done with it you can free the memory using delete.

Wednesday, 14 October 2009

Reading string via cin and flushing input buffers

The following program shows three different approaches to read string via Cin. It also shows two different approaches for flushing input buffer.






//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to read input string and to flush input buffer
#include<iostream>
#include<string>
#include <istream>
#include <limits>

using namespace
std;

int
main()
{

string s1;
cout << "\nAPPROACH 1" <<endl;
cout << "Input a string : ";
cin >> s1;
cout << "Entered string = " <<s1.c_str()<<endl;

//Lets flush the buffer from Approach 1 here
istream& in(cin);
in.ignore( numeric_limits<std::streamsize>::max(), '\n' );

cout << "\nAPPROACH 2" <<endl;
cout << "Input a string : ";
istreambuf_iterator<char> eos; // end-of-range iterator
istreambuf_iterator<char> iit (cin.rdbuf()); // stdin iterator
string s2;
while
(iit!=eos && *iit!='\n') s2+=*iit++;
cout << "Entered string = " << s2 << endl;

//Another approach for flushing the input
int ch;
while
((ch = cin.get()) != '\n' && ch != EOF);

cout << "\nAPPROACH 3" <<endl;
cout << "Input a string : ";
char
buf[BUFSIZ];
if
(cin.getline(buf, sizeof(buf)))
{

cout << "Entered string = " << buf << endl;
}


cout << endl;
return
0;
}







The output is as follows:



More information:

Thursday, 8 October 2009

Using #pragma message directive

Sometimes you would like to remind the user or yourself of something while compiling and there is an option to remind yourself using the #pragma message directive. See the following program:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to remember things using #pragma message
#include<iostream>

using namespace
std;

int
someFunction(int a=0, int b=0)
{

#pragma message("TODO: Coding of someFunction()")
return 0;
}


int
main()
{

someFunction();
return
0;
}

In this case the user wants to remind himself that someFunction() needs to be coded at a later time and hence he uses a preprocessor message statement. The result is when compilation is done, a message will be output as shown below:

Tuesday, 6 October 2009

Using Preprocessor Statements #ifdef, #elif, #else and #endif

Sometimes it becomes necessary to write two (or more) different peices of behaviour in a common code. Depending of its mode/place/time/version the behaviour has to be changed. It can be done by the use of simple preprocessor statements. Consider the following program:






//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show use of preprocessor macros for dynamic behaviour

#include<iostream>
#include<string>

using namespace
std;

#define USE_CAR //Comment or Uncomment this if using preprocessor option

int
main()
{

int
someNum = 3;
#ifdef USE_CAR
string modeOfTransport("Use a Car");
#elif USE_BUS
string modeOfTransport("Use a Bus");
#elif USE_TRAIN
string modeOfTransport("Use a Train");
#else
string modeOfTransport("Use any mode of transport");
#endif

cout<<"Mode of Transport = "<<modeOfTransport<<" and someNum = "<<someNum<<endl;

return
0;
}



The output is as follows:

In the program above, the statement in the start #define USE_CAR says that the code with USE_CAR should be used during compile time. Instead if USE_BUS is defined, that particular peice of code will be used. If nothing is defined then the behaviour with else will be used.

There is another way to use these preprocessor directives. It is by defining in the properties below. If defined this way then the statement should be omitted from the main program.


The output is as follows in this case:

For more information see this.

Wednesday, 30 September 2009

Passing Variable arguments in functions

Sometimes it becomes necessary to have variable number of arguments in the function. One way is to overload the function but that may be unnecessary for simple logic. We can use access variable-argument lists macros in the functions. Here is a simple example:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to use variable number of arguments

#include<iostream>
#include <stdarg.h> //needed for va_ macros
using namespace std;

//List Should be terminated by -1 in our case
int Add(int a,...)
{

int
total = a;
int
l_ParamVal=0;

//Declare a va_list macro and initialize it with va_start
va_list l_Arg;
va_start(l_Arg,a);

while
((l_ParamVal = va_arg(l_Arg,int)) != -1)
{

total+= l_ParamVal;
}


va_end(l_Arg);
return
total;
}


int
main()
{

cout<<"Result of Add(2) = "<<Add(2, -1)<<endl;
cout<<"Result of Add(2, 3) = "<<Add(2, 3, -1)<<endl;
cout<<"Result of Add(2, 3, 31) = "<<Add(2, 3, 31, -1)<<endl;
cout<<"Result of Add(2, 3, 31, 77) = "<<Add(2, 3, 31, 77, -1)<<endl;

cout<<endl;
return
0;
}

These type of functions that take variable number of arguments are also referred to as 'Variadic Functions'. See more details here.

The output is as follows:

Friday, 25 September 2009

Passing unnamed arguments in functions

It is possible to pass an unnamed argument in C++ function. The unnamed argument indicates that argument is unused. Typically unnamed arguments arise from the simplification of code or from planning ahead for extensions. In either case, leaving the argument in place, although unused, ensures that the callers are not affected by the change. Simple example as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of unnamed arguments
#include<iostream>

using namespace
std;

void
someFunc(int a, int)
{

cout<<"Only a is defined to "<<a<<endl;
cout<<"The second argument is dummy"<<endl;
}


int
main()
{

someFunc(15, 100); //100 is dummy

cout<<endl;
return
0;
}






The output is as follows:

Tuesday, 22 September 2009

Converting Decimal Integer to Hexadecimal String using C++

I often encounter situations where I want to convert an Integer value to a Hexadecimal value. Now if it was just for storing, it doesnt really matter as internally decimal and hex values are the same. If it was just printing, its again very straightforward. But the problem I have is to convert it into string value (or chars[]) and use them later. I found a simple program to do this. Here it is:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of program that does int to hex string
//Adapted from http://www.dreamincode.net/forums/showtopic19694.htm
#include<iostream>
#include <stack>

using namespace
std;

string int2hex(unsigned int dec)
{

int
i = 0;
stack <int>remainder;
string hex, temp;
char
hexDigits[] = { "0123456789abcdef" };

if
(dec == 0)
hex = hexDigits[0];

while
(dec != 0)
{

remainder.push(dec % 16);
dec /= 16;
++
i;
}


while
(i != 0)
{

if
(remainder.top() > 15)
{

temp = int2hex(remainder.top());
hex += temp;
}

hex.push_back(hexDigits[remainder.top()]);
remainder.pop();
--
i;
}

return
hex;
}



int
main()
{

unsigned int
dec = 4294967295;
string hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 123456789;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 100;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 15;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 0;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
cout<<endl;
return
0;
}





The output is as follows:

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:


Sunday, 13 September 2009

Advanced features of C++ functions

There are 3 advanced features of C++ functions as compared to C. They are Call by Reference, Function Overloading and Default Arguments. You can read more about them here.

A simple program showing all the three features as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of pointer to const and const pointer
#include<iostream>

using namespace
std;

//Call by reference
void swap(int& a, int &b)
{

int
temp = a;
a = b;
b = temp;
}


//Overloaded function: Call by reference (pointers)
void swap(int *a, int *b)
{

int
temp = *a;
*
a = *b;
*
b = temp;
}


//Pass by value with Default arguments
void doSwap(int a, int b = 1)
{

swap(a,b);
cout<<"After Local Swap: a = "<< a <<" b = "<< b <<endl;
}


int
main()
{

int
a = 10, b = 17;
cout<<"Before Swap : a = "<< a <<" b = "<< b <<endl;
swap(a, b);
cout<<"After Swap 1: a = "<< a <<" b = "<< b <<endl;
swap(&a, &b);
cout<<"After Swap 2: a = "<< a <<" b = "<< b <<endl;
doSwap(a, b);
doSwap(a);
cout<<"After DoSwap: a = "<< a <<" b = "<< b <<endl;

return
0;
}






The output is as follows:


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:

Tuesday, 8 September 2009

Getting Date and Time in C++ on Windows

The program example below shows three aproaches to get the date and time. MSDN references are embedded in the program.


#include<iostream>
#include<time.h> //For approach1 and approach3
#include <Windows.h> //For approach 2

using namespace
std;

void
approach1(void)
{

char
dateStr [9];
char
timeStr [9];
//http://msdn.microsoft.com/en-us/library/585kfedd(VS.80).aspx
_strdate_s( dateStr);
//http://msdn.microsoft.com/en-us/library/yb2bth04(VS.80).aspx
_strtime_s( timeStr );
cout<<"\nApproach 1"<<endl;
cout<<"Current date is: "<<dateStr<<endl;
cout<<"Current time is: "<<timeStr<<endl;
}


void
approach2(void)
{

SYSTEMTIME systemTime;
//http://msdn.microsoft.com/en-us/library/ms724390(VS.85).aspx
GetSystemTime(&systemTime);
cout<<"\nApproach 2"<<endl;
cout<<"Current date is: "<<systemTime.wMonth<<"/"<<systemTime.wDay<<"/"<<systemTime.wYear<<endl;
cout<<"Current time is: "<<systemTime.wHour<<":"<<systemTime.wMinute<<":"<<systemTime.wSecond<<endl;
}


void
approach3(void)
{

//http://www.daniweb.com/forums/thread64803.html
char buffer[BUFSIZ] = { '\0' } ;
time_t now = time( &now ) ;
struct
tm local_time;
//http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx
localtime_s( &local_time, &now ) ;
cout<<"\nApproach 3"<<endl;
//http://msdn.microsoft.com/en-us/library/fe06s4ak(VS.71).aspx
strftime( buffer, BUFSIZ, "%m/%d/%Y", &local_time ) ;
cout<<"Current date is: "<< buffer << endl ;
strftime( buffer, BUFSIZ, "%H:%M:%S", &local_time ) ;
cout<<"Current time is: "<< buffer << endl ;
}


int
main()
{

approach1();
approach2();
approach3();
return
0;
}






The output is as follows:

Friday, 4 September 2009

Changing objects in 'const member functions' via Mutable

We saw last time an example of 'Const Member Functions' (also known as 'Inspectors'). In contrast the member functions without the const suffix are known as 'non-const member functions' or 'mutators'.

Sometimes it may be necessary to modify a data member (variable or object in your class) in a const member function. There are two approaches to do that. One is to use the const_cast and the other to use 'mutable'. I use both the approaches in the example below:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to change objects in const member functions
#include<iostream>

using namespace
std;

class
ABC
{

public
:
int
func1(int a, int b);
int
func2(int a, int b) const;
private
:
int
x;
mutable
int y;
};


int
ABC::func1(int a, int b)
{

x = a, y = b;
cout<<"x = "<<x<<" and y = "<<y<<endl;
return
0;
}


int
ABC::func2(int a, int b) const
{

//x = a; - COMPILE ERROR because its const
int *temp = const_cast<int*>(&x); //Removing the const
*temp = a; //OK now
y = b; //OK because its defined as mutable
cout<<"x = "<<x<<" and y = "<<y<<endl;
return
0;
}


int
main()
{

ABC abc;
abc.func1(3, 7);
abc.func2(20, 40);
return
0;
}



The output is as follows:


Monday, 31 August 2009

Reading and Writing from Windows Registry

The following is an example of reading and writing from Windows Registry using C++. The code have been created based on examples from MSDN. I have provided the MSDN references in the code in case you want to lookup the documentation.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of reading and writing from registry
#include <windows.h>
#include <iostream>

using namespace
std;

#define WIN_32_LEAN_AND_MEAN

void
writeToRegistry(void)
{

DWORD lRv;
HKEY hKey;

//Check if the registry exists
//http://msdn.microsoft.com/en-us/library/ms724897(VS.85).aspx
lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_WRITE,
&
hKey
);


if
(lRv != ERROR_SUCCESS)
{

DWORD dwDisposition;

// Create a key if it did not exist
//http://msdn.microsoft.com/en-us/library/ms724844(VS.85).aspx
lRv = RegCreateKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
, //"Use Multi-Byte Character Set" by using L
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&
hKey,
&
dwDisposition
);


DWORD dwValue = 1;

//http://msdn.microsoft.com/en-us/library/ms724923(VS.85).aspx
RegSetValueEx(
hKey,
L"Something"
,
0
,
REG_DWORD,
reinterpret_cast
<BYTE *>(&dwValue),
sizeof
(dwValue)
);


//http://msdn.microsoft.com/en-us/library/ms724837(VS.85).aspx
RegCloseKey(hKey);
}
}


void
readValueFromRegistry(void)
{

//Example from http://msdn.microsoft.com/en-us/library/ms724911(VS.85).aspx

HKEY hKey;

//Check if the registry exists
DWORD lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_READ,
&
hKey
);


if
(lRv == ERROR_SUCCESS)
{

DWORD BufferSize = sizeof(DWORD);
DWORD dwRet;
DWORD cbData;
DWORD cbVal = 0;

dwRet = RegQueryValueEx(
hKey,
L"Something"
,
NULL,
NULL,
(
LPBYTE)&cbVal,
&
cbData
);


if
( dwRet == ERROR_SUCCESS )
cout<<"\nValue of Something is " << cbVal << endl;
else
cout<<"\nRegQueryValueEx failed " << dwRet << endl;
}

else

{

cout<<"RegOpenKeyEx failed " << lRv << endl;
}
}


int
main()
{

writeToRegistry();
readValueFromRegistry();
return
0;
}


The output is as follows: