Tuesday, March 25, 2014

How to Convert CString to TCHAR*

There are two methods for converting a CString variable to TCHAR* variable

Basically CString belongs to ATL/MFC shared class / DLL you can convert CString into either string or a TCHAR variable of <tchar.h>

The exmaple below shows two implementations

#include<iostream>
#include<atlmfc.h>
#include<tchar.h>

int main( )
{

  CString strMyCS1("This is Method 1");

 TCHAR* pszmyTCHAR1=new TCHAR[strMyCS1.GetLength( )+1];

_tcscpy(pszmyTCHAR1,strMyCS1);

_tprintf("\n %s",pszmyTCHAR1);

delete[ ] pszmyTCHAR; //It is importatnt to use delete if you use new keyword

CString strMyCS2(_T("This is Method 2"));

TCHAR* pszmyTCHAR2=strMyCS2.GetBuffer( );

_tprintf("\n %s",pszmyTCHAR2);

strMyCS2.ReleaseBuffer( );

system("pause");

return 0;

}

output:

This is Method 1
This is Method 2
press any key....






Using brace initialization for any class, struct, or union VC++ 2013

In modern C++, you can use brace initialization for any type, without the equals sign.You can use brace initialization for any class, struct, or union. If a type has a default constructor, either implicitly or explicitly declared, you can use default brace initialization (with empty braces). For example, the following class may be initialized by using both default and non-default brace initialization:

#include<string>
#include<iostream>
using namespace std;

class CBraceInitializer
{
public:
CBraceInitializer(){ cout << "\nThis is Empty constructor Initializer"; }
CBraceInitializer(string StringVar) :m_mystring{ StringVar }{ cout << "\nString intilaized:" << m_mystring; }
CBraceInitializer(int IntVar, double Doublevar) :m_myint{ IntVar }, m_mydouble{ Doublevar }
{
cout << "\nInteger intilaized:" << m_myint << "\nDouble Initialized:" << m_mydouble;
}
CBraceInitializer(string StringVar, double Doublevar) :m_mystring{ StringVar }, m_mydouble{ Doublevar }
{
cout << "\nString intilaized:" << m_mystring;
cout<<"\nDouble Initialized:" << m_mydouble;
}
CBraceInitializer(string StringVar, double Doublevar, int IntVar) :m_mystring{ StringVar }, m_mydouble{ Doublevar }, m_myint{ IntVar }
{
cout << "\nString intilaized:" << m_mystring;
cout << "\nDouble Initialized:" << m_mydouble;
cout << "\nInteger intilaized:" << m_myint<<"\n";
}
int m_myint;
string m_mystring;
double m_mydouble;
};

int main()
{
CBraceInitializer objCBraceInitializer1{};
CBraceInitializer objCBraceInitializer2;

CBraceInitializer objCBraceInitializer3{"Brace String Intializer"};
CBraceInitializer objCBraceInitializer4("Function String Intializer");

CBraceInitializer objCBraceInitializer5{1,0.01};
CBraceInitializer objCBraceInitializer6(2,0.02);

CBraceInitializer objCBraceInitializer7{"Brace init with Double",0.03};
CBraceInitializer objCBraceInitializer8("Function init with Double", 0.04);

CBraceInitializer objCBraceInitializer9{ "Brace init with Double&int", 0.05,3 };
CBraceInitializer objCBraceInitializer10("Function init with Double&int", 0.06,4);

system("pause");

return 0;

}

output:

This is Empty constructor Initializer
This is Empty constructor Initializer
String intilaized:Brace String Intializer
String intilaized:Function String Intializer
Integer intilaized:1
Double Initialized:0.01
Integer intilaized:2
Double Initialized:0.02
String intilaized:Brace init with Double
Double Initialized:0.03
String intilaized:Function init with Double
Double Initialized:0.04
String intilaized:Brace init with Double&int
Double Initialized:0.05
Integer intilaized:3

String intilaized:Function init with Double&int
Double Initialized:0.06
Integer intilaized:4
Press any key to continue . . .

Thursday, March 20, 2014

C++ Program to Find Week Number of a Given Date

The program gives the week number of a Given Date Where Weeks are ISO weeks Starts on Sunday and Ends on Saturday

#include<windows.h>
#include<time.h>
#include<iostream>
#include<conio.h>
#include<tchar.h>
#include <string>
#include<atltime.h>
#include<tchar.h>
using namespace std;
#define SECONDS_IN_A_DAY 86400
#define ConfigIntervalDays 7
int dayofweek(int d, int m, int y);
int getMonthEndDay(int Month,int Year);
bool checkIfLeapYear(int Year);
int WeekofYearFinder(int Day,int Month,int Year);
enum DayOfWeek {Sun=0,Mon,Tue,Wed,Thr,Fri,Sat};
void main()
{
time_t tmNow = time(NULL);
    CTime tmCurrent(tmNow);      
     
      CTime         tmStartOfDay(tmCurrent.GetYear(),tmCurrent.GetMonth(),tmCurrent.GetDay(),1,0,0);
      CTime nPrevEndTime = tmStartOfDay.GetTime();
      CTime nPrevStartTime = tmStartOfDay.GetTime() - ConfigIntervalDays*SECONDS_IN_A_DAY;
 int Year,Month,Day;
      Year=nPrevStartTime.GetYear();
      Month=nPrevStartTime.GetMonth();
      Day=nPrevStartTime.GetDay();
 int i=WeekofYearFinder(Day,Month,Year);
Year= nPrevEndTime.GetYear();
Month=nPrevEndTime.GetMonth();
     Day=nPrevEndTime.GetDay();
 int j=WeekofYearFinder(Day,Month,Year);
 if(i==j)
 {
 cout<<"\n Both Start Time and End Time Belongs to same week";
 cout<<"\n Week:"<<i;
 }
 else
 {
          cout<<"\n Start Time and End Time Belongs to different weeks";
 cout<<"\n Start Time Week:"<<i;
 cout<<"\n End Time Week:"<<j;
 }
 getch();
}

int dayofweek(int d, int m, int y)
{
    static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    y -= m < 3;
    return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

int getMonthEndDay(int Month,int Year)
{
   int daysInMonth=0;
   switch(Month)
   {
   case  2:
        daysInMonth = checkIfLeapYear(Year) ? 29 : 28;
        break;
   case 4:
   case 6:
   case 9:
   case 11:
         daysInMonth = 30;
         break;
   default:
          daysInMonth = 31;
          break;
   }
  return daysInMonth;
}

bool checkIfLeapYear(int Year)
{
return (!(Year % 4) && (Year % 100)) || !(Year % 400);
}

int WeekofYearFinder(int Day,int Month,int Year)
{
  if(Day<1|| Day>31 ||Month<1||Month>12||Year<1000)
  {
return 0;
  }
   int wofy=0;
   bool breakFlag=false;
   int EndDay;
   int PrevMonthEnd=0;
   int PrevMonthEndDay=0;
   for(int j=1;j<=12;j++)
   {
     EndDay=getMonthEndDay(j,Year);//Get the Day number which Month Ends Eg:31/MM/YYYY
if(j>1)
{
PrevMonthEnd=dayofweek(PrevMonthEndDay,j-1,Year);//Get the Day number which Previous Month Ends Eg:30/MM/YYYY
}
for(int i=1;i<=EndDay;i++)
{
       if(i==1)//check if day is 1/MM/YYYY
  {
  if((dayofweek(i,j,Year)>Sun && !(PrevMonthEnd<=Sat))||j==1)//Check if  Day 1 > sunday and Previous Month not Ends in Sunday
  {
             wofy++;
  }
  else if(dayofweek(i,j,Year)==Sun)//Check if Day 1 is Sunday
      {
           wofy++;
      }
  }
  else if(dayofweek(i,j,Year)==Sun)//Check Which are the other days other than Day 1 falls on Sunday
  {
           wofy++;
  }

      if(i==Day && j==Month)//If Iteration matches to Given Date exits entire loop
 {
 breakFlag=true;
 break;
 }
}
if(breakFlag)
{
break;
}
PrevMonthEndDay=getMonthEndDay(j,Year);
//Sets the Previous Month's End Date Day Number Eg: 30/MM/YYY
   }
return wofy;
}

Friday, March 14, 2014

How to Concatenate or Append TCHAR Strings

#include<windows.h>
#include<vector>
#include<map>
#include<list>
#include<conio.h>
#include<tchar.h>
using namespace std;

void main(void)
 {

TCHAR* String1;

TCHAR* String2;

TCHAR* String3;

TCHAR* Mystring;

String1="Hi  ";
String2="Welcome  ";
String3="to Know My C++ Blog";

_stprintf(Mystring,_T("%s%s%s"),String1,String2,String3);

_tprintf("\n\n Mystring:%s",Mystring);

getch( );
}

Output:
Mystring:Hi Welcome to Know My C++ Blog



Tuesday, March 11, 2014

C++/VC++ Program to Move a File to Folder and Move a Folder to Folder

//MoveTest.CPP
#include<windows.h>
#include<iostream>
#include<conio.h>
#include<tchar.h>
using namespace std;
void MoveFiletonewLoc(void);
void MoveFoldertonewLoc(void);
int main()
{
int choice;
cout<<"\n********File and Directory mover*********\n\n";
cout<<"1.Move File to another location\n";
cout<<"2.Move Folder to another location";
cout<<"\n\n Enter your choice:";
cin>>choice;
switch(choice)
{
case 1:MoveFiletonewLoc();
break;
case 2:MoveFoldertonewLoc();
break;
   default:cout<<"\nWrong Choice";
            exit(0);
}
getch();
return 0;
}

void MoveFiletonewLoc(void)
{
TCHAR Source[256];
memset(Source,0,256);
    TCHAR Destination[256];
memset(Destination,0,256);
_tprintf("\n\nEnter the file location:");
_tscanf("%s",Source);
_tprintf("\n\nEnter the destination location:");
_tscanf("%s",Destination);
int i=MoveFile(Source,Destination);//Moves Files to Folder
if(i>0)
{
_tprintf("\n\nFile moved to location %s Sucessfully",Destination);
}
else
{
_tprintf("\n\nFile moved to location %s UnSucessful",Destination);
}
}

void MoveFoldertonewLoc(void)
{
TCHAR Source[256];
memset(Source,0,256);
    TCHAR Destination[256];
memset(Destination,0,256);
_tprintf("\n\nEnter the folder location:");
_tscanf("%s",Source);
_tprintf("\n\nEnter the destination location:");
_tscanf("%s",Destination);
SHFILEOPSTRUCT fop={};
fop.wFunc=FO_MOVE;
fop.pFrom=Source;
fop.pTo=Destination;
if(!SHFileOperation(&fop))//Moves Folder to Folder
{
_tprintf("\n\nFolder moved to location %s Sucessfully",Destination);
}
else
{
_tprintf("\n\nFolder moved to location %s UnSucessful",Destination);
}
}

OUTPUT:




Monday, March 10, 2014

COMMONLY USED HEADER FILES IN VISUAL C++


WINDOWS.H is a master include file that includes other Windows header files, some of which also
include other header files. The most important and most basic of these header files are:


  •  WINDEF.H         :Basic type definitions.
  •  WINNT.H           :Type definitions for Unicode support.
  •  WINBASE.H       :Kernel functions.
  •  WINUSER.H       :User interface functions.
  •  WINGDI.H          :Graphics device interface functions.

These header files define all the Windows data types, function calls, data structures, and constant
identifiers. They are an important part of Windows documentation. You might find it convenient to use
the Find In Files option from the Edit menu in the Visual C++ in Visual Studio to search through these
header files. You can also open the header files in the Developer Studio and examine them directly.

Some of the header Files like Shalwapi.h , audiomediatype.h ,Bits.h ,Error.h etc... are defined in Windows Platforms SDK

For that you see ProgramFiles->Microsoft SDKs->Windows->v6.0A->Include

This will appear only if you install Windows Platform SDK or Visual Studio 2010 or Higher

Hello World Equivalent in WIndows API

//HelloBlog.CPP

#include <windows.h>

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello, Welcome to Know My C++ BLOG!"), TEXT ("KNOW MY C++ BY SREEYUSH"), 0) ;
return 0 ;
}

Sunday, March 9, 2014

How to Compare two CASE SENSITIVE TCHAR Strings are equal or not? if _tcscmp() not working fine

#include <windows.h>
#include <iostream>
#include "Shlwapi.h"
#include <tchar.h>
#include <conio.h>

using namespace std;
void main( void )
{
TCHAR *String1="This is my String";
TCHAR *String2="This iS my String";
int m_equality=0;
int ScanLineLength,EndLineLength;
ScanLineLength = _tcslen(String1);
EndLineLength=_tcslen(String2);
  if (ScanLineLength==EndLineLength)
  {
    for (int k=0;k<EndLineLength;k++)
    {
      if (String1[k]!=String2[k])
       {
  break;
  }
 else
 {
         m_equality++;
       }
     }
    if(m_equality==EndLineLength)
    {
      cout << "Both Strings are Equal";
    }
   else
    {
      cout << "Both Strings are not Equal";
    }
 }
  else
  cout << "Both Strings are not Equal";
getch();
}

OUTPUT:
Both Strings are not Equal

Note : if you use _tcscmp( ) or _tcsicmp( )  both are case insensitive comparers

Saturday, March 8, 2014

Shlwapi.h not found or FilePathRemoveSpec or Linker Error of FilePathRemoveSpec Solved

 I Solved the Problem with including Shlwapi.h and Using FilePathRemoveSpec

I did the Following Steps

1. Install Microsoft Platform SDK

After installing it you will get a Folder like this in your Program Files

Srep 1:You will Find a folder named Microsoft SDKs in your program files






















Step 2: Check whether Shlwapi.h is Included in that folder Windows->v6.0->Include





















Step 3: Add Path to VC++ Directories both Include and Lib






























































Step 4: Add External dependencies for the project


























Step 5 : Browse there and Type Shlwapi.lib in the Window and Click ok

Now your Visual Studio Can run the Following code works Fine :

#include <windows.h>
#include <iostream>
#include <conio.h>
#include "Shlwapi.h"

void main( void )
{
// Path to include file spec.
char buffer_1[ ] = "C:\\TEST\\sample.txt"; 
char *lpStr1;
lpStr1 = buffer_1;

// Print the path with the file spec.
cout << "The path with file spec is          : " << lpStr1 << endl;

// Call to "PathRemoveFileSpec".
PathRemoveFileSpec(lpStr1);

// Print the path without the file spec.
cout << "\nThe path without file spec is       : " << lpStr1 << endl;
getch();
}

OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt

The path without file spec is       : C:\TEST






























Using _strdup , _tcsdup , _mbsdup

The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.
_wcsdup and _mbsdup are wide-character and multibyte-character versions of _strdup. The arguments and return value of _wcsdup are wide-character strings; those of _mbsdup are multibyte-character strings. These three functions behave identically otherwise.

_UNICODE & _MBCS not defined:Use _strdup  defined in <string.h>
_MBCS defined:Use _mbsdup defined in <mbstring.h>
_UNICODE defined: Use _wcsdup defined in <string.h> or <wchar.h>
TCHAR.H routine : Use _tcsdup

Syntax:
char *_strdup(const char *strSource);
char *_tcsdup(const char *strSource);
wchar_t *_wcsdup(const wchar_t *strSource);
unsigned char *_mbsdup(const unsigned char *strSource);

strSource:
Null-terminated source string.
Return Value:
Each of these functions returns a pointer to the storage location for the copied string or NULL if storage cannot be allocated.
Example:
// _strdup.c
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
void main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   printf( "Original: %s\n", buffer );
   newstring = _strdup( buffer );
   printf("Copy:     %s\n", newstring );
   free( newstring );
   getch();
}

Output:
Original: This is the buffer text
Copy:This is the buffer text



// _tcsdup.cpp
#include <string.h>
#include <iostream.h>
#include <malloc.h>
#include <conio.h>
int main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   cout<< "Original:"<< buffer;
   newstring = _strdup( buffer );
   cout<<"Copied string:"<<newstring;
   free(newstring);
   getch();
return 0;
}
Output:
Original: This is the buffer text
Copied string:This is the buffer text


Friday, March 7, 2014

Usage of #pragma comment in Visual C++ & C++/CLI

Adding the Pragma Directives  will tell the linker what additional input files are needed. The link will link the object files generated by the compiler and link them with the additional libraries to generate the ultimate module(.exe or .dll files).
This work can also be done in the properties dialog of the project. You can add the .lib files in the property below:
Configuration Properties -> Linker -> Input -> Additional Dependencies.
The input files will be part of the linker command in the end. Below is a simple sample shows how the input files are used in the link command:
link /dll a.obj b.lib c.lib
In short Places a comment record into an object file or executable file.

Syntax:
#pragma comment( comment-type [,"commentstring"] )

comment-type

1.compiler:Places the name and version number of the compiler in the object file
2. exestr:  At link time this string is placed in the executable file
3.lib:Places a library-search record in the object file. 
4.linker:Places a linker option in the object file.
5.user:Places a general comment in the object file

Examples:

#pragma comment( lib, "emapi" ) //lib comment-type
#pragma comment( compiler ) //compiler comment type
#pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )  //user comment type


For more reference see also:

http://msdn.microsoft.com/en-us/library/7f0aews7.aspx


Sunday, March 2, 2014

Do I need a copy constructor?

Standard C++ makes heavy use of copy constructors because they are needed to support proper memory management. Referring to ref objects through handles, coupled with garbage collection, means that you don’t need copy constructors nearly as often in C++/CLIIn standard C++ the compiler will give you a default copy constructor if you do not pro-vide one. This is not the case in C++/CLI, so if you want to provide copy construction for your classes, you will need to write a copy constructor.

// UsingTrackingRefrence.cpp : main project file.

#include "stdafx.h"

using namespace System;

ref class MyClass
{
int value;
String ^str;
public:
MyClass(int v, String ^s) :value(v), str(s){}

MyClass(const MyClass %other)
{
Console::WriteLine("Copy constructor Called");
value = other.value;
str = other.str;
}
int getValue(){ return value; }
void setvalue(int v){ value = v; }
String ^getString(){ return str; }
};

int main(array<System::String ^> ^args)
{
    Console::WriteLine("\nCopy Construction");
MyClass ^one = gcnew MyClass(1, "Class One");

MyClass ^onecopy1 = one;
       Console::WriteLine("\nValue of Copy one Class:Value:{0},Str:{1}", onecopy1->getValue(),                        onecopy1->getString());
MyClass onecopy2 = *one;
onecopy2.setvalue(4);
Console::WriteLine("\nValue of one:{0}", one->getValue());
Console::WriteLine("\nValue of oneCopy2:{0}", onecopy2.getValue());
Console::WriteLine("\nStr of one:{0}", one->getString());
Console::WriteLine("\nStr of oneCopy2:{0}", onecopy2.getString());
Console::ReadKey();
    return 0;
}

OutPut:

Copy Construction

Value of copy one Class:Value:1,Str:Class one
Copy constructor called

Value of one:1
Value of oneCopy2:4

Str of one:Class one
Str of oneCopy2:Class one


Saturday, March 1, 2014

Implementing the destructor and finalizer for a class in C++

Destructor:

A destructor is executed when you no longer need an object. To provide a destructor for a class, add a member function that has the same name as the class but is preceded by a tilde character (~).

Finalizer :

Finalizers are called when the garbage collector finally reclaims the object’s memory. You will need a finalizer if you have unmanaged resources, such as pointers to unmanaged classes, file handles, window handles, graphic device contexts, and so on. If you don’t have any of those—and you’ll only tend to do that when you are working with unmanaged code—you probably don’t need a finalizer.

A finalizer is a member function that has the same name as the class but is preceded by an exclamation mark (!).

//MyClass.h Header File
using namespace System;
ref class MyClass
{
String ^name;
public:
MyClass(String ^objectName); // constructor
~MyClass(); // destructor
!MyClass(); // finalizer
void DoSomething(); // 'work' method
};

///MyClass.CPP File

#include "stdafx.h"
using namespace std;
#include "MyClass.h"

MyClass::MyClass(String ^objectName)
{
name = objectName;
Console::WriteLine("Constructor called for {0}", name);
}

MyClass::~MyClass()
{
Console::WriteLine("Destructor called for {0}", name);
}

MyClass::!MyClass()
{
Console::WriteLine("Finalizer called for {0}", name);
}

void MyClass::DoSomething()
{
Console::WriteLine("DoSomething called for {0}", name);
}

//Using the finalizer in Main Program

#include "MyClass.h"
int main(array<System::String^>^ args)
{
MyClass ^m1 = gcnew MyClass("m1");
m1->DoSomething();
Console::WriteLine();
Console::WriteLine("End of program");
Console::WriteLine();
return 0;
}

Output similar to the following appears:

Constructor for m1
DoSomething called
End of Program
Finalizer called for m1




Member initialization lists in Constructor VC++

Here We Can Take a Simple Example of Credit Card Dummy Code:

//Create A headrer File Named CreditCardAccount.h Copy This code to that
ref class CreditCardAccount
{
public:
CreditCardAccount(long number, double limit);
void SetCreditLimit(double amount);
bool MakePurchase(double amount);
void MakeRepayment(double amount);
void PrintStatement();
long GetAccountNumber();

private:
long AccountNumber;
double CurrentBalance;
double CreditLimit;
};

********************************************************************
//Create A CPP File Named CreditCardAccount.CPP Copy This code to that

#include "stdafx.h"
#include "CreditCardAccount.h"

#using <mscorlib.dll>
using namespace System;

void CreditCardAccount::SetCreditLimit(double amount)
{
CreditLimit = amount;
Console::Write("\nCredited Amount:");
Console::Write(amount);
}

bool CreditCardAccount::MakePurchase(double amount)
{
if (CurrentBalance + amount > CreditLimit)
{
return false;
}
else
{
CurrentBalance += amount;
return true;
}
}

void CreditCardAccount::MakeRepayment(double amount)
{
CurrentBalance -= amount;
Console::Write("\nPaid Amount:");
Console::Write(amount);
}

void CreditCardAccount::PrintStatement()
{
Console::Write("\nCurrent Balance:");
Console::Write(CurrentBalance);
}

long CreditCardAccount::GetAccountNumber()
{
return AccountNumber;
}

CreditCardAccount::CreditCardAccount(long number, double limit)
:AccountNumber(number),CreditLimit(limit),CurrentBalance(0.0)
{
}//Member initialization lists in Constructor

##############################################################
//Create A CLR PROJECT named "CreditOrganizer " Copy This code to

// CreditOrganizer.cpp : main project file.

#include "stdafx.h"
#include "CreditCardAccount.h"

using namespace System;

int main(array<System::String ^> ^args)
{
CreditCardAccount ^myAccount;
myAccount = gcnew CreditCardAccount(1235,2500);
myAccount->SetCreditLimit(1000);
myAccount->MakePurchase(1000);
myAccount->MakeRepayment(7000);
long num = myAccount->GetAccountNumber();
Console::Write("\nAccount Number:");
Console::Write(num);
myAccount->PrintStatement();
Console::ReadKey();
    return 0;
}


How to Generate Random Occurance of a Number in C++?

You can use Microsoft's Inbuilt Data-type Called Random in C++/CLI

// RandomNumberOccurance.cpp : main project file.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
Random ^r = gcnew Random();//This is inbuilt data type in MS VC++
int randomnumber;
int throws = 0;
do{
randomnumber = r->Next(1, 7);
Console::WriteLine(randomnumber);
throws++;
} while (randomnumber != 6);

Console::Write("You took");
Console::Write(throws);
Console::Write("To get 6");
Console::ReadKey();
    return 0;
}

This program shows random occurance of number 6 by taking interval from 1 to 7 , thorws shows the count at which time 6 occurs in random tries