Friday, May 13, 2011

Some C++ Tips and Functions



A simple C++ function to tokenize a string



#include <vector>
#include <string>
#include <sstream>
using namespace std;
vector<string>  getTokens(string str){
 string buf;  // Have a buffer string
 stringstream ss(str);  // Insert the string into a stream
 vector tokens;  // Create vector to hold our words
 while (ss >> buf)
    tokens.push_back(buf);
 return tokens;
}





A more complex tokenize function


void Tokenize(const string& str,
                      vector& tokens,
                      const string& delimiters = " ")
{
     // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
     // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);
    while (string::npos != pos || string::npos != lastPos)
    {
         // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
         // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
         // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
Usage:

 vector<string> tokens;
  string str("Split,me up!Word2 Word3.");
  Tokenize(str, tokens, ",<'> " );
  vector <string>::iterator iter;
  for(iter = tokens.begin();iter!=tokens.end();iter++){
    cout<< (*iter) << endl;
 }

Write a number to a string

int                   myInteger;
string              myString;
ostringstream myStream;
 // Copy Integer to String Stream
myStream << myInteger;
 // Assign characters in stream to std::string
myString = myStream.str();
A stream can be cleared in the following way:
myStream.str("");

Replace a vector element

vector  theVector;
 //populate the vector
theVector.at(2) = "new string";

Transform HTML color code string to COLORREF

The string parameter is assumed to be in '#FFFFFF' format.
COLORREF transformHTML(string color){
 string s1(color, 1,2);
 string s2(color, 3,2);
 string s3(color, 5,2);

 long r = strtol(s1.c_str(), NULL, 16);
 long g = strtol(s2.c_str(), NULL, 16);
 long b = strtol(s3.c_str(), NULL, 16);

 return RGB (r,g,b);
}

Determine Whether A String is in Upper Case

bool isUpper(string line){
 const char *str = line.c_str();
 while(*str != '\0'){
  if(IsCharLower(*str))
   return false;
  *str++;
 }
 return true;
}
A Windows IsCharLower function is used.

Convert str::string to char

Use the c_str() function.

Example:

string str = "test string";
const char *ch = str.c_str();

Pass string arrays to functions

This actually refers to C.
You declare a string array in the calling function as follows:
 char arr[10][30];
The second dimension must always have the exact number of elements in the function declaration:
 int functionName(char  (*arr) [30], int numberOfElements 10);
The brackets around the array name are important. You also pass the number of elements in the first dimension as an argument to the function.

Wednesday, March 25, 2009

Make Sure Only One Instance of the Application Is Running

Place the following code in your WinMain:

// Look for the running instance of the application
char* szTitle = "My Title";
if (FindWindow(NULL, szTitle)){
SetForegroundWindow(FindWindow(NULL, szTitle));
return FALSE;
}

First, it looks for a window that has the same title as your application. If it finds it, it will make it active.
Another approach is to use a mutex:

BOOL IsFirstInstance()
{
HANDLE hMutex = CreateMutex(NULL, FALSE, "PUT A GUID HERE");
if(hMutex && GetLastError() == ERROR_ALREADY_EXISTS)
{
ReleaseMutex(hMutex);
return FALSE;
}
ReleaseMutex(hMutex);
return TRUE;
}

You call the above-mentioned function in your "InitInstance" method of your application.

How to Launch Internet Properties Control Applet

Use the following code:

WinExec("rundll32 inetcpl.cpl LaunchConnectionDialog", SW_SHOW);

Measure Time In Milliseconds

Use the DWORD GetTickCount(void) function.
The return value is the number of milliseconds that have elapsed since the system was started.
Example Code:

DWORD dwStart = GetTickCount();

Stop if this has taken too long:

if( GetTickCount() - dwStart >= TIMELIMIT )
Cancel();

Measure Time In Milliseconds

Use the DWORD GetTickCount(void); function.


The return value is the number of milliseconds that have elapsed since the system was started.


Example Code:


DWORD dwStart = GetTickCount();



Stop if this has taken too long:


if( GetTickCount() - dwStart >= TIMELIMIT )

Cancel();

Retrieve Menu Item Text with GetMenuItemInfo function


MENUITEMINFO MenuItem;
HMENU hmenu, hsubmenu;
HWND hwnd; //handle to main window
char szString[256];
int countLast =0;
//Initialize MENUITEMINFO structure:
memset(&MenuItem,0, sizeof(MenuItem));
MenuItem.cbSize = sizeof(MenuItem);
MenuItem.fMask =MIIM_TYPE;
MenuItem.fType = MFT_STRING;
//Important - the dwTypeData and cch data members must also be initialized to receive the string.
MenuItem.cch = 256;
MenuItem.dwTypeData = szString;
hmenu = GetMenu(hwnd); //get the menu
hsubmenu = GetSubMenu(hmenu,0); //get the first submenu

countLast = GetMenuItemCount(hsubmenu); //count number of items in the submenu; starts with 0;

GetMenuItemInfo(hsubmenu, 0, --countLast, &MenuItem );

MessageBox(NULL, MenuItem.dwTypeData, "Last Menu Item", MB_OK);

Use Bold or Underlined Font

1. Define a static HFONT variable:

static HFONT hFont;

2. In the response to the WM_INITDIALOG message, create a font with desired features, using CreateFont function:

HFONT CreateFont(
int nHeight, // logical height of font
int nWidth, // logical average character width
int nEscapement, // angle of escapement
int nOrientation, // base-line orientation angle
int fnWeight, // font weight
DWORD fdwItalic, // italic attribute flag
DWORD fdwUnderline, // underline attribute flag
DWORD fdwStrikeOut, // strikeout attribute flag
DWORD fdwCharSet, // character set identifier
DWORD fdwOutputPrecision, // output precision
DWORD fdwClipPrecision, // clipping precision
DWORD fdwQuality, // output quality
DWORD fdwPitchAndFamily, // pitch and family
LPCTSTR lpszFace // pointer to typeface name string
);


Use the pre-defined FW_BOLD parameter for fnWeight for Bold text.
Set fdwUnderline parameter to TRUE for underlined text.

Use default values for most of the other parameters.

Here is a simple helper function:

HFONT SimpleCreateFont( int Height, BOOL Bold, BOOL Italic, BOOL Underline,
BOOL StrikeOut, DWORD Family, char* FaceName )
{
HFONT Ret;
int Weight;
Weight = Bold ? FW_BOLD : FW_NORMAL;
Ret = CreateFont( Height, 0, 0, 0, Weight,
Italic, Underline, StrikeOut, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | Family, FaceName );
return( Ret );
}


3. Use the WM_SETFONT message to tell child control to use new font

SendMessage( GetDlgItem( hwnd, ID_WEB ), WM_SETFONT, (WPARAM)hFont, 0 );