Strings and Vectors

Create a set of utility functions, WelcomeMessage & WelcomeMessage

Page 1 of 1

4 Replies - 628 Views - Last Post: 02 March 2010 - 09:16 PM Rate Topic: -----

#1 1983hotrod24  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 16-January 08

Strings and Vectors

Posted 02 March 2010 - 08:05 PM

This is my first post, so bare with me until I get it setup correctly.

This is in C++. I am trying to add a WelcomeMessage and WelcomeMessageBox method. I need to format a Welcome Message with a Header and Author along with the current date. They are suppose to use the Split and FormatOutput methods to assist in the display. I have all the methods prewritten, I am just unsure how to implement them. Those methods are in the Util2.h file.

I am receiving this - error C2661: 'MessageBox' : no overloaded function takes 3 arguments. If I take out calling the MessageBox method, it compiles. I am having trouble calling this method as well.

/////////////////////////////////////////////////////////////////////////////////////
//
// Company Name     : BailesSoft
// Department Name  : Computer and Information Sciences 
// File Name        : Util.h
// Classes          :
// Purpose          : Declares a set of utility free functions and the Menu class
// Author           : Rodney Harris
// Create Date      : Tuesday, March 2, 2010
//
//-----------------------------------------------------------------------------------
//
// Modified Date    : Tuesday, March 2, 2010
// Modified By      : Rodney Harris
//
/////////////////////////////////////////////////////////////////////////////////////
#pragma once

#pragma warning (disable:4231)
#pragma warning (disable:4251)

#include <cstdlib>
#include <fstream>		    // fstream object
#include <sstream>		    // stringstream class
#include <string>		    // for string objects
#include <iostream>			// cin and cout
#include <cassert>		    // assert()
#include <cctype>		    // for classifying characters
#include <iomanip>
#include <conio.h>
#include <ostream>
#include <windows.h>
#include <wincon.h>
#include <ctime>
#include <climits>
#include <cmath>
#include <algorithm>
//#include <regex>
//#include <random>


using namespace std;
using namespace tr1;

const   int	    MAX_ENTRIES    = 14;
const   char	TAB	    	= '\t';

const	int	    FRed	    = FOREGROUND_RED | FOREGROUND_INTENSITY;
const	int	    FBlue	    = FOREGROUND_BLUE | FOREGROUND_INTENSITY;	
const	int	    FGreen	    = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
const	int 	FWhite	    = FRed | FBlue | FGreen;
const	int 	FYellow	    = FGreen | FRed;
const	int		FBlack		= FOREGROUND_INTENSITY;

const	int	    BRed	    = BACKGROUND_RED | BACKGROUND_INTENSITY;
const	int	    BBlue	    = BACKGROUND_BLUE | BACKGROUND_INTENSITY;
const	int 	BGreen	    = BACKGROUND_GREEN | BACKGROUND_INTENSITY;
const	int	    BWhite	    = BRed | BBlue | BGreen;
const	int 	BYellow	    = BRed | BGreen;
const	int		BGray		= BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN;	

string		Today ( );												// Today's date
string		Now ( );												// Current time
void		Center (string strS);									// Center arg on current line
void		clrscr ( );												// clears the screen
void		gotoxy (int, int);										// places the cursor atv position (x,y)
COORD		getxy ( );											    // returns current coordinates of cursor 
void		SetColor (int nFore = FBlue,	
					    int nBack = BWhite);						// Sets foreground and background colors
int 		Max (const int[ ], const int);						// Find the largest number
int 		Min (const int[ ], const int);						// Find smallest number
float		Average	(const int[ ], const int);					// Find the average
void 		PressAnyKey (const string& = "continue");			// waits for user to press a key
void 		Skip	(const int N = 1);								// Insert N "endl" in cout
void 		Swap (int&, int&);										// Reference parms required since parms changed
void 		Selection (int [ ], const int);						// Selection sort - recursive
void 		Insertion (int [ ], const int);						// Insertion sort
void		Sink	(int [ ], const int);							// Sinking (bubble) sort
void		QuickSort (int [ ], const int);						// Quick Sort
void		QuickSort (int [ ], const int, const int);			// Sort left or right in Quick
int  		Search (const int [ ], const int, const int);		// Linear search
int  		BinSearch (const int [ ], const int, const int);	// Binary search
bool		OK (const int, const int, const int);				// Is int in proper range?
bool 		CheckIt	(void);											// Check for cin errors
bool		CheckFile (istream& Input);							// Check for istream errors
string		Toupper   (string& strS);								// changes all characters in a string to uppercase
char		Toupper	(char& cC);									// changes a single character to uppercase
string		Tolower	(string& strS);								// changes all characters in a string to lowercase
char		Tolower	(char& cC);									// changes a single character to lowercase
void		StripBoth (string& strS, char cC = ' ');				// strips whitespaces from both sides of S
string		Strip (string& strP, char cC = ' ');					// strips whitespace without changing the string
void		Getline	(string& Str, int Length, char CStr = '\n');	// gets a line from keyboard
void		Getline	(fstream& F, string& Str, int Length, 
					 char CStr = '\n');							//fstream input
string		ReplaceAll(string& strS, const string strOld, 
					   const string strNew);						//Replace all occurrences of strOld in strS with strNew
int			MessageBox(const string strMsg, const string strCaption);	

class		 Menu
{
   protected:
		int		NumEntries;
		string	MenuTitle;
		string	MenuEntries [MAX_ENTRIES];

	public:
 		Menu  	(const string &astring);                  		// Constructor function
		Menu  	operator+  (const string &astring)const;			// Add item to the menu
		Menu& 	operator+= (const string &astring);				// Add item to the menu

		int   	GetChoice  (void) const;  				   		// Display menu & return valid choice
		Menu  	operator-  (const int)const;						// Delete an item from the menu
		Menu& 	operator-= (const int);			        		// Delete an item from the menu

		friend  ostream& operator<< (ostream& Fileout, const Menu &MyMenu);
};


/////////////////////////////////////////////////////////////////////////////////////
//
// Department Name  : Computer and Information Sciences 
// File Name        : Util.cpp
// Purpose          : Define a set of utility functions and the Menu class
// Author           : Rodney Harris
// Create Date      : Tuesday, March 2, 2010
/////////////////////////////////////////////////////////////////////////////////////
#include	"Util.h"

/* Standard error macro for reporting API errors */
#define PERR(bSuccess, api){if(!(bSuccess)) printf("%s:Error %d from %s \
    on line %d\n", __FILE__, GetLastError(), api, __LINE__);}

//////////////////////////////////////////////////////////////////////////
// 
// Function name     : clrscr
// Description       : Clears the screen and places the cursor at top left
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : There are no arguments
// 
//////////////////////////////////////////////////////////////////////////
void clrscr( )
 {
	HANDLE	hConsole  = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD	coordScreen = { 0, 0 };       /* here's where we'll home the cursor */
    BOOL	bSuccess;
    DWORD	cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;	    /* to get buffer info */
    DWORD	dwConSize;                     /* number of character cells in the current buffer */

    /* get the number of character cells in the current buffer */
    bSuccess	= GetConsoleScreenBufferInfo( hConsole, &csbi );
    PERR( bSuccess, "GetConsoleScreenBufferInfo" );
    dwConSize	= csbi.dwSize.X * csbi.dwSize.Y;

    /* fill the entire screen with blanks */
    bSuccess   = FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',
                        dwConSize, coordScreen, &cCharsWritten );
    PERR( bSuccess, "FillConsoleOutputCharacter" );

    /* get the current text attribute */
    bSuccess   = GetConsoleScreenBufferInfo( hConsole, &csbi );
    PERR( bSuccess, "ConsoleScreenBufferInfo" );

    /* now set the buffer's attributes accordingly */
    bSuccess   = FillConsoleOutputAttribute( hConsole, csbi.wAttributes,
                        dwConSize, coordScreen, &cCharsWritten );
    PERR( bSuccess, "FillConsoleOutputAttribute" );

    /* put the cursor at (0, 0) */
    bSuccess   = SetConsoleCursorPosition( hConsole, coordScreen );
    PERR( bSuccess, "SetConsoleCursorPosition" );

    return;
 }




//////////////////////////////////////////////////////////////////////////
// 
// Function name     : gotoxy
// Description       : Places the cursor at the position (nX,nY) on the 
//                        screen
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int nX
// Argument          : int nY
// 
//////////////////////////////////////////////////////////////////////////
 void gotoxy (int nX, int nY)
{
	HANDLE	hConsole   = GetStdHandle(STD_OUTPUT_HANDLE);
	BOOL	bSuccess;
	COORD	coordScreen;
	coordScreen.X	    = (SHORT) nX;
	coordScreen.Y	    = (SHORT) nY;
    bSuccess           = SetConsoleCursorPosition( hConsole, coordScreen );
    PERR( bSuccess, "SetConsoleCursorPosition" );
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : getxy
// Description       : Returns the (X,Y) coordinates of the current 
//                        cursor position.  This is as a COORD object 
//                        with X and Y components
// 
//------------------------------------------------------------------------
// 
// Return type       : COORD
// Argument          : There are no arguments
// 
//////////////////////////////////////////////////////////////////////////
COORD	getxy ( )
{
	 COORD		                Coordinates;
	 HANDLE		                hConOut			=	GetStdHandle(STD_OUTPUT_HANDLE);
	 CONSOLE_SCREEN_BUFFER_INFO	*pBuffer	=	new	CONSOLE_SCREEN_BUFFER_INFO;
	 GetConsoleScreenBufferInfo(hConOut, pBuffer);
	 Coordinates.X		=	pBuffer -> dwCursorPosition.X;
	 Coordinates.Y		=	pBuffer -> dwCursorPosition.Y;
	 delete		pBuffer;
	 return		Coordinates;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : SetColor
// Description       : Set foreground and background colors
//                        See list of colors in Util.h
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int nFore - foreground color
// Argument          : int nBack - background color
// 
//////////////////////////////////////////////////////////////////////////
void SetColor (int nFore, int nBack)
{
	HANDLE	hConsoleOutput   = GetStdHandle (STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute (hConsoleOutput,  (WORD) (nFore | nBack) );
	return;
}

 

//////////////////////////////////////////////////////////////////////////
// 
// Function name     : StripBoth
// Description       : Strips , by default , blanks from both sides of 
//                        argument and leaves the result in the argument
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : string& strS  - in/out argument to be stripped
// Argument          : char cC       - character to strip
// 
//////////////////////////////////////////////////////////////////////////
void StripBoth (string& strS, char cC)
{
	if ((int)strS.length( ) == 0)					// If empty string, return
		return;

	int		iPos,	
			iPos2;
	iPos	= (int) strS.find_first_not_of (cC);
	
	if (iPos == (int) string :: npos)				// If only delimiters found
	{												//		set to null and return
		strS	= "";										
		return;
	} // if (iPos == string :: npos)				// If only delimiters found

	iPos2		= (int) strS.find_last_not_of (cC);
	if (iPos2 != (int) string::npos  && iPos2 < (int) strS.length()-1)
		strS	= strS.erase (iPos2+1);

	if (iPos != (int) string::npos && iPos > 0)
	    strS	    = strS.erase (0,iPos);
    return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Strip
// Description       : Strip leading/trailing characters (blanks by 
//                        default) from the argument and returns the 
//                        result.  The argument is unchanged.
// 
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : string& strP  - input string
// Argument          : char cC       - character to strip
// 
//////////////////////////////////////////////////////////////////////////
string Strip (string& strP, char cC)
{
	string	strS	= strP;

	if ((int) strS.length( ) == 0)				// If empty string, return
		return	strS;

	int		iPos;	
			
	iPos	    = (int)strS.find_first_not_of (cC);
	if (iPos == (int) string :: npos)				// If only delimiters found
	{												//		set to null and return
		strS	= "";										
		return	strS;
	} // if (iPos == string :: npos)				// If only delimiters found
	
	if (iPos > 0)
		strS    = strS.erase(0, iPos);

	iPos	    = (int) strS.find_last_not_of (cC);
	if (iPos < (int) strS.length() - 1)
	strS	    = strS.erase (iPos+1);
	
	return	strS;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Toupper
// Description       : Changes the all letters in the entire string 
//                          strS to uppercase and returns the result. 
//                          The original is unchanged.
// 
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : string& strP - input string
// 
//////////////////////////////////////////////////////////////////////////
string Toupper (string& strP)
{
	int		nLength;
	string	strS	= strP;
	nLength			= (int) strS.length();

	for(int nI = 0; nI < nLength; nI++)
		if (int(strS[nI]) > 96 && int(strS[nI]) < 123)
			strS[nI] = char(int(strS[nI]) - 32);
	
    return	strS;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Toupper
// Description       : Changes the character argument to an uppercase
// 
//------------------------------------------------------------------------
// 
// Return type       : char
// Argument          : char& cC
// 
//////////////////////////////////////////////////////////////////////////
char Toupper (char& cC)
{
	if (int(cC) > 96 && int(cC) < 123)
		cC = char(int(cC) - 32);
	return	cC;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Tolower
// Description       : Changes the all letters in the entire string 
//                          strS to lowercase and returns the result. 
//                          The original is unchanged.
// 
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : string& strP
// 
//////////////////////////////////////////////////////////////////////////
string Tolower (string&	strP)
{
	int		nLength;
	string	strS	= strP;
	nLength			= (int) strS.length ( );

	for(int nI = 0; nI < nLength; nI++)
		if (int (strS[nI]) > 64 && int (strS[nI]) < 91)
			strS[nI] = char (int (strS[nI]) + 32);

	return	strS;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Tolower
// Description       : Returns the lower case equivalent of the argument
// 
//------------------------------------------------------------------------
// 
// Return type       : char
// Argument          : char& cC
// 
//////////////////////////////////////////////////////////////////////////
char Tolower (char& cC)
{
	if (int (cC) > 64 && int (cC) < 91)
			cC = char(int (cC) + 32);

	return	cC;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Getline
// Description       : Retrieves an entire string from the keyboard.
//					        It uses as a default terminating character: '\n'
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : string&   strS       - input goes here
// Argument          : int       nLength    - max number of characters
// Argument          : char      cC         - delimiter
// 
//////////////////////////////////////////////////////////////////////////
void Getline (string& strS, int nLength, char cC)
{
	assert (nLength > 0);

	string	    strTemp;	
	char*	    cArray = new char[nLength+10];

	cin.getline(cArray, nLength, cC);
	strTemp		= cArray;

	strS		= strTemp;
	delete []  cArray;
	return;
}




//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Getline
// Description       : Retrieves an entire string from the file fsF.
//					        It uses as a default terminating character: '\n'
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : fstream&  fsF        - input file
// Argument          : string&   strS       - input goes here
// Argument          : int       nLength    - max length of input
// Argument          : char      cC         - delimiter
// 
//////////////////////////////////////////////////////////////////////////
void Getline (fstream& fsF, string& strS, int nLength, char cC)
{
	assert (nLength > 0);

	string	strTemp;
	char*	cArray	= new char[nLength+10];
	fsF.getline(cArray, nLength, cC);
	strTemp			= cArray;
	strS			= strTemp;
	delete [] cArray;
	return;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : ReplaceAll
// Description       : Replace all occurences of strOld in strS 
//							with strNew 
// 
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : string& strS
// Argument          : const string strOld
// Argument          : const string strNew
// 
//////////////////////////////////////////////////////////////////////////
string ReplaceAll(string& strS, const string strOld, const string strNew)
{
    string	strTemp		= strS;
    int     nCol;

    nCol    = (int) strTemp.find(strOld);
    while (nCol != (int) string :: npos)
    {
        strTemp	= strTemp.replace(nCol, strOld.length(), strNew);
        nCol	= (int) strTemp.find(strOld);
    }

    return	strTemp;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Max
// Description       : Finds the largest integer in an array A of nN 
//                        integers and returns the position in the 
//                        array where it is found
// 
//------------------------------------------------------------------------
// 
// Return type       : int
// Argument          : const int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
int  Max (const int A[ ], const int nN)
{
	int 	nL = 0;					// Subscript of the largest value in A

	for (int nM = 1; nM < nN; nM++)
		if (A[nM] > A [nL])  
			nL = nM;

	return nL;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Min
// Description       : Finds the smallest integer in an array A of nN 
//                        integers and returns the position in the 
//                        array where it is found
// 
//------------------------------------------------------------------------
// 
// Return type       : int
// Argument          : const int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
int  	Min (const int	A[ ], const int	nN)
{
	int 	nS = 0;					// Subscript of the smallest value in A

	for (int nM = 1; nM < nN; nM++)
		if (A[nM] < A [nS])  
			nS = nM;

	return nS;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : PressAnyKey
// Description       : Displays a Press any key to ... message and clears
//                        the screen after a key is pressed
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : const string& strS   - message as part of "Press...
// 
//////////////////////////////////////////////////////////////////////////
void PressAnyKey (const string&	strS)
{
	Skip(2);
	HANDLE	                    hConsole  = GetStdHandle (STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO	csbi;						/* to get buffer info */
	BOOL		                bSuccess  = GetConsoleScreenBufferInfo( hConsole, &csbi );
	PERR (bSuccess, "GetConsoleScreenBufferInfo" );
	int		nY = csbi.srwindow.Bottom - 1;
	int		nX = (csbi.srwindow.Right - (int) strS.length( ) - 
                    (int)((string)("Press any key to ")).length( ))/2;

	gotoxy (nX, nY);
	cout    << "Press any key to " << strS;
	nX = _getch  ( );
	clrscr  ( );
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Skip
// Description       : Skip nN lines on the screen; nN is 1 by default
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
void   Skip (const int nN)
{
	if (nN < 1) 
		return;

	if (nN > 50)
	{
		clrscr( );
		return;
	}

	for (int nM = 1; nM <= nN; nM++)
		cout << endl;

	return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Swap
// Description       : Exchange the two integer arguments; because 
//                        the values of the arguments will change, 
//                        they must be passed by reference
//
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int& nX
// Argument          : int& nY
// 
//////////////////////////////////////////////////////////////////////////
void 	Swap (int& nX, int& nY)
{
	int     nTemp	= nX;
	nX		    	= nY;
	nY			    = nTemp;

	return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Selection
// Description       : Performs selection sort on an array A of nN 
//                        integers.  This is a recursive implementation.
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
void  Selection (int A[ ], const int nN)
{
	if (nN <= 1) 
		return;

	int nM	= Max (A, nN);  	    // Find the largest

	if (A[nM] != A[nN-1])			// If largest is not already last
		Swap (A[nM], A[nN-1]);		//      Swap largest with last

	Selection (A, nN-1);  		    // Perform selection on remaining items using recursion
	return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Insertion
// Description       : Insertion sort of nN integers in array A
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int A[ ]
// Argument          : int nN
// 
//////////////////////////////////////////////////////////////////////////
void Insertion ( int A[ ], int nN )
{
	int	nTmp;
	int	nP, nJ;

    for (nP = 1; nP < nN; nP++)
    {
        nTmp	= A[nP];

        for (nJ = nP; nJ > 0 && nTmp < A[nJ - 1]; nJ--)
            A[nJ]	= A[nJ - 1];

        A[nJ]	= nTmp;
    }  // end  for
}	// end  Insertion



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : QuickSort
// Description       : Quicksort routine to sort an array A of nN elements
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
void  QuickSort (int A[ ], const int nN)
{
	QuickSort (A, 0, nN-1);
	return;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : QuickSort
// Description       : Recursive helper function for the QuickSort above
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int A[ ]
// Argument          : const int nStart
// Argument          : const int nEnd
// 
//////////////////////////////////////////////////////////////////////////
void  QuickSort (int A[ ], const int nStart, const int nEnd)
{
	int	    nLeft	= nStart,
			nRight	= nEnd;

	if (nLeft >= nRight)										// If set is empty or one item, quit
			return;

	while (nLeft < nRight)										// Partition into "Right" and "Left" sets
	{
		while ((A[nLeft] <= A[nRight]) && (nLeft < nRight))	// If in order,
			nRight --;											//       move from Right

		if (nLeft < nRight)										// If more than 1, exchange
			Swap (A[nLeft], A[nRight]);

		while ((A[nLeft] <= A[nRight]) && (nLeft < nRight))	// If in order,
			nLeft++;											//       move from left

		if (nLeft < nRight)			                        // If more than 1, exchange
			Swap (A[nLeft], A[nRight]);
	} // while (nLeft < nRight)			    // Partition into "Right" and "Left" sets
    
	QuickSort (A, nStart, nLeft - 1); 	    // Recursively sort "Left" partition
	QuickSort (A, nRight + 1, nEnd);		    // Recursively sort "Right" partition
	return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Sink
// Description       : Bubble (Sinking) Sort - sort an array A of nN 
//                        integers into ascending order
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
void  Sink (int A[ ], const int nN)
{
	bool 	bSorted	    = false;					// Assume A not yet sorted

	int	    nPass		= 0;
	int	    nM;

	while (!bSorted && (nPass < nN))				// Sort til done or enough passes
	{
		nPass++;
		bSorted		= true;							// Assume sorted til proved wrong

		for (nM = 0; nM < (nN - nPass); nM++)
			if (A[nM] > A[nM + 1])					// If out of order then
			{
				Swap (A[nM], A[nM + 1]);			//      exchange
				bSorted = false;					//      set not Sorted indicator
			}	// end if

	}	// end while
 	return;
}	// end Sink



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Search
// Description       : Locates argument nKey in array A of nN elements; 
//                        returns the location where nKey is found; 
//                        returns -1 if not found;
//						    Linear search algorithm used
// 
//------------------------------------------------------------------------
// 
// Return type       : int
// Argument          : const int A[ ]
// Argument          : const int nN
// Argument          : const int nKey
// 
//////////////////////////////////////////////////////////////////////////
int  Search (const int A[ ], const int nN, const int nKey)
{
	int	    nM;
	bool	bFound	= false;

	for (nM = 0; ((nM < nN) && !bFound); nM++)
		if (nKey == A[nM]) 
			bFound = true;

	if (bFound)	
		return (nM - 1);
	else			
		return (-1);
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : BinSearch
// Description       : Locates argument nKey in array A of nN elements; 
//                        returns the location where nKey is found; 
//                        returns -1 if not found;
//						    Binary search algorithm used.  Note: A must be 
//                           sorted into ascending order for this
//                           algorithm to work properly.
// 
//------------------------------------------------------------------------
// 
// Return type       : int
// Argument          : const int A [ ]
// Argument          : const int nN
// Argument          : const int nKey
// 
//////////////////////////////////////////////////////////////////////////
int  BinSearch (const int A [ ], const int nN, const int nKey)
{
	int	    nU	    = nN - 1,
			nL	    = 0,
			nM	    = 0;

	bool	bFound	= false;

	while ( !bFound && (nL <= nU))
	{
		nM  = (nL + nU)/2;								// Find midpoint

		if (nKey == A [nM])	bFound	= true;			// If found we are through
		else if (nKey < A [nM])	nU	= nM - 1;		// else discard the correct half
			  else					nL	= nM + 1;
	}

	if (bFound) 
		return	nM;
	else		   
		return	-1;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Today
// Description       : Returns today's date as a string in the form of
//                        February 02, 2005
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : There are no arguments
// 
//////////////////////////////////////////////////////////////////////////
string	Today ( )
{
	__time64_t 	Curr;
	tm 				tmLocal;
	_time64 (&Curr); 					// get current time_t 
	_localtime64_s(&tmLocal, &Curr);	// dereference, assign
	string			strMonths[12] = {"January",  "February",    "March",
									   "April",    "May", "June", "July",
									   "August",   "September",   "October",
									   "November", "December"};
	string			strMon, strDay, strYear, strToday;
	stringstream	strS, strT;
	strMon			= strMonths[tmLocal.tm_mon];
	strS << tmLocal.tm_mday;
	strS >> strDay;
	strT << tmLocal.tm_year + 1900;
	strT >> strYear;
	return	strMon + " " + strDay + ", " + strYear;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Now
// Description       : Returns the current time as a string in the form of
//					        hh:mm:ss am/pm
// 
//------------------------------------------------------------------------
// 
// Return type       : string
// Argument          : There are no arguments
// 
//////////////////////////////////////////////////////////////////////////
string	Now ( )
{
	__time64_t 	Curr;
	tm 				tmLocal;
	_time64 (&Curr); 					// get current time_t 
	_localtime64_s(&tmLocal, &Curr);	// dereference, assign

	string			strHour, strMinute, strSecond, strAMorPM = " AM";
	stringstream	strH, strM, strS;
	int				nHour =	tmLocal.tm_hour % 12;
	if (nHour == 0)
		nHour		= 12;
	if (tmLocal.tm_hour > 11)
		strAMorPM	= " PM";
	strH	<< nHour;
	strH	>> strHour;
	strM	<< tmLocal.tm_min;
	strM	>> strMinute;
	if (tmLocal.tm_min < 10)
		strMinute	= (string) "0" + strMinute;
    strS << tmLocal.tm_sec;
	strS >> strSecond;
	if (tmLocal.tm_sec < 10)
		strSecond	= (string) "0" + strSecond;
	
	return  strHour + ":" + strMinute + ":" + strSecond + strAMorPM;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : OK
// Description       : Check to find if an int is in a specified range
// 
//------------------------------------------------------------------------
// 
// Return type       : bool
// Argument          : const int nTestVal
// Argument          : const int nLoBound
// Argument          : const int nHiBound
// 
//////////////////////////////////////////////////////////////////////////
bool  OK (const int nTestVal, const int nLoBound, const int nHiBound)
{
	if ((nTestVal >= nLoBound) && (nTestVal <= nHiBound))
		return	true;
	else
		return	false;
}




//////////////////////////////////////////////////////////////////////////
// 
// Function name     : CheckIt
// Description       : Tests the error flags in the cin input stream to
//                        determine if an error has occurred on input;  
//                        if no error flag was set, it returns "true".  
//                        Otherwise, it displays a series of messages that 
//                        identify the error, show the error text, reset the
//                        error flags, and flush up to 256 characters
//                        from the input buffer up to the next endline 
//                        character.  In this latter case, it returns"false".
// 
//------------------------------------------------------------------------
// 
// Return type       : bool
// Argument          : void
// 
//////////////////////////////////////////////////////////////////////////
bool  CheckIt (void)
{
	if (!cin.fail( )) return true;

	char 	cX[257];

	cout 	<< "\n\nThe input operation failed because"
			<< " invalid key(s) were pressed."
			<< "\nThe error status is " << cin.fail( );

	cin.clear( );				// Reset error flags in the input stream
	cin.getline (cX,256);     // Clear input buffer (unless > 256 chars typed)

	cout 	<< "\n\nThe invalid input is (" << cX << ")";
	cout	<< "\n\nThe program will continue with the value(s) in\n"
			<< "the input variable(s) that follow the error unchanged." << endl;

	cout	<< "\n\nWARNING:  Your program results MAY be incorrect "
			<< "\nor the program may crash because of the error!";

	PressAnyKey ( );
	return	false;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : CheckFile
// Description       : Check to see if a file input operation had errors; 
//                        return true if not; return false if so, 
//                        and clear the errors. 
// 
//------------------------------------------------------------------------
// 
// Return type       : bool
// Argument          : istream& isInput
// 
//////////////////////////////////////////////////////////////////////////
bool CheckFile (istream& isInput)
{
	if (!isInput.fail( )) return true;

	isInput.clear( );              		// Reset error flags in the input stream
	isInput.ignore(INT_MAX, '\n'); 		// Clear input buffer to end of line

	return	false;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Average
// Description       : Find the average of nN integers in an array
// 
//------------------------------------------------------------------------
// 
// Return type       : float
// Argument          : const int A[ ]
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
float  Average (const int	A[ ], const int nN)
{
	float  fAns = 0.0;

	for (int nM = 0; nM < nN; nM++)
		fAns	+= (float) A[nM];

	if (nN > 0) fAns	= fAns / (float) nN;

	return	fAns;
}


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Center
// Description       : Display strS centered on the current line of the 
//						        screen
// 
//------------------------------------------------------------------------
// 
// Return type       : void
// Argument          : string strS
// 
//////////////////////////////////////////////////////////////////////////
void	Center (string strS)
{
	COORD	coordC	= getxy ( );
	gotoxy ((80 - (int) strS.length( ))/2, coordC.Y);
	cout	<< strS;
	return;
}



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Menu::Menu
// Description       : Construct a menu object with the specified title
// 
//------------------------------------------------------------------------
// 
// Return type       : None
// Argument          : const string &strNewTitle
// 
//////////////////////////////////////////////////////////////////////////
Menu :: Menu (const string &strNewTitle)	// Initialize empty menu with NewTitle
{
	NumEntries = 0;					    // The menu is empty at this point
	MenuTitle  = strNewTitle;			    // Assign a title for the menu
}	// end Menu constructor



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : operator<<
// Description       : Overload the (friend) insertion operator for menus
//			               to display menu title and numbered menu items
// 
//------------------------------------------------------------------------
// 
// Return type       : ostream&
// Argument          : ostream&  fsFileout
// Argument          : const     Menu       &MyMenu
// 
//////////////////////////////////////////////////////////////////////////
ostream& operator<< (ostream& fsFileout, const Menu &MyMenu)
{
	int		nN;

	string	strTempDay = Today( );

	SetColor(FRed);
	clrscr( );
	nN		= 75 - (int) strTempDay.length( ) - 1;
	gotoxy (nN, 1);
	fsFileout << strTempDay;

	gotoxy (10, 3);
	fsFileout << MyMenu.MenuTitle;
	gotoxy (10, 4);
	for (nN = 1; nN <= (int) MyMenu.MenuTitle.length( ); nN++)		// Underline the title
			fsFileout << '-';

	Skip(2);
	fsFileout << right;
	SetColor( );

	for (nN = 0; nN < MyMenu.NumEntries; nN++)
		 fsFileout	<< "\t" << setw(2) << (nN+1)	
					<< ". "
					<< MyMenu.MenuEntries[nN] 	
					<< endl;
	fsFileout << resetiosflags (ios :: right);

	return (fsFileout);
}  // end overloaded friend operator<<



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : const Menu::operator+
// Description       : Add a new entry to a menu object, after checking 
//                        if there is room for it
// 
//------------------------------------------------------------------------
// 
// Return type       : Menu
// Argument          : const string &strEntry
// 
//////////////////////////////////////////////////////////////////////////
Menu Menu :: operator+ (const string &strEntry) const    // Add Entry to menu
{
	Menu	Temp ("Temporary");                          // Create a temporary menu Temp
	Temp	= *this;                                     // Copy *this menu into Temp menu

	assert(NumEntries < MAX_ENTRIES);                    // Verify menu not full

	Temp.MenuEntries [ NumEntries ] = strEntry;			 // Add new entry to bottom
	Temp.NumEntries++;                                   // Update the count of entries
	return	Temp;
} // end operator +



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Menu::operator+=
// Description       : dd a new entry to the menu object, after checking 
//                        if there is room for it.	 Use the previously 
//                        overloaded + to do most of the work
// 
//------------------------------------------------------------------------
// 
// Return type       : Menu&
// Argument          : const string &strEntry
// 
//////////////////////////////////////////////////////////////////////////
Menu& Menu :: operator+= (const string &strEntry)	// Add Entry to menu
{
	*this	= *this + strEntry;						// Using overloaded + defined above
	return *this;
}  // end operator +=



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : const Menu::GetChoice
// Description       : Display the menu, get the choice, validate it, 
//                        and return it to user.  Uses the overloaded 
//                        friend operator << to display the menu
// 
//------------------------------------------------------------------------
// 
// Return type       : int
// Argument          : void
// 
//////////////////////////////////////////////////////////////////////////
int	Menu :: GetChoice (void) const    // Display menu and return a valid choice
{
	int 	nAns = 0;

	if (NumEntries <= 0)
		return  0;             			// If menu empty, return 0 (false)


	
    while (NumEntries)					// Do FOREVER - the "return" exits
	{
		cout  << *this                 // Using overloaded << for menus
			   << "\n\n\tPlease type the number of your choice from the menu: ";

		SetColor(FRed);
		cin >> nAns;				    // Get the answer
		SetColor( );

		clrscr ( );

		if (CheckFile(cin) && OK(nAns, 1, NumEntries))  // Is the choice valid?
			return  nAns;  // Return choice if it is valid
			
		Skip (2);
		cout 	<< "\tYour response (";
		SetColor(FRed);
		cout	<< nAns;
		SetColor( );
		cout	<< ") is not a number between ";
		SetColor(FRed);	
		cout	<< "1 ";
		SetColor( );
		cout	<< "and ";
		SetColor(FRed);
		cout	<< NumEntries;
		SetColor ( );
		cout	<< ".\n\n\tPlease try again.";
		PressAnyKey ( );
	}  // end while (forever)
	return nAns;

}   // end GetChoice


//////////////////////////////////////////////////////////////////////////
// 
// Function name     : const Menu::operator-
// Description       : Delete an existing item from a menu, verifying 
//                        that it exists first
// 
//------------------------------------------------------------------------
// 
// Return type       : Menu
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
Menu Menu :: operator- (const int nN) const 				// Delete item N from the menu
{
	Menu	Temp ("Temporary");							// Create a temporary menu Temp
	Temp	= *this;										// Copy *this menu into Temp menu

	assert ((nN > 0) && (nN <= NumEntries));				// Check for valid value in N

	for (int nM = nN-1; nM < Temp.NumEntries; nM++)		// Move remaining entries
		Temp.MenuEntries [nM] = Temp.MenuEntries [nM+1];	//  up to fill vacant slot

	Temp.NumEntries--;										// Decrement number of entries

	return Temp;
}  // end operator-



//////////////////////////////////////////////////////////////////////////
// 
// Function name     : Menu::operator-=
// Description       : Remove an item from the menu using the previously 
//                        overloaded - operator
// 
//------------------------------------------------------------------------
// 
// Return type       : Menu&
// Argument          : const int nN
// 
//////////////////////////////////////////////////////////////////////////
Menu& Menu :: operator-= (const int nN)   // Delete item N from the menu
{
	*this	= *this - nN;			        // Using overloaded - defined above
	return	*this;
}  // end operator -=

 






//////////////////////////////////////////////////////////////////////////
// 
// Function name     : MessageBox
// Description       : Call MessageBox with message: strMsg,  
//                        caption: strHdg, OK button, and standard style.
// 
//------------------------------------------------------------------------
// 
// Return type			: int
// Argument			: const string - the message
// Argument			: const string - the heading
// 
//////////////////////////////////////////////////////////////////////////
int   MessageBox(const string strMsg, const string strHdr)
{
	return MessageBox(NULL, (strMsg+TAB).c_str(), strHdr.c_str(), MB_OK|MB_ICONINFORMATION|MB_TOPMOST|MB_SETFOREGROUND);
}


/////////////////////////////////////////////////////////////////////////////////////
//
// Department Name  : Computer and Information Sciences 
// File Name        : Util.cpp
// Purpose          : Define a set of utility functions & methods.
// Author           : Rodney Harris
// Create Date      : Tuesday, March 2, 2010
/////////////////////////////////////////////////////////////////////////////////////

#include	"Util.h"

//Method declarations
/*
FindMatches(const string& strln, const string& str Pattern):vector<string>
FormatOutput(const string& strMessage, int nLeftMargin, int nRightMargin):string
Goodbye(const string& strMessage, const string& strHeading):void
GoodbyeBox(const string& strMessage, const string& strHeading):void
Join(const vector<string> strV, const char cSep):string
Match(const string& strln, const string& strRegEx):bool
Split(const string& strlnput, const string& strDelims):vector<string>
WelcomeMessage(const string& strMessage, const string& strHeading, const string& strAuthor):void
WelcomeMessageBox(const string& strMessage, const string& strHeading, const string& strAuthor):void
*/


/*
   Rodney Harris
   Last Modification Dare:	Tuesday, March 2, 2010
   email: harrisrc@goldmail.etsu.edu
   Purpose: This is the 2nd example main .cpp for practicing & reviewing C++
			using strings and vectors.
*/

#include "Util.h"

void WelcomeMessage();
void WelcomeMessageBox();
void main()
{
	int n;
	SetColor();
	clrscr();


	cout << "\n\n\nStarting pt :)/>\n";
	cin >> n;
	MessageBox( NULL, L"Lab 2 ", L"This is ");

	PressAnyKey();
}


This post has been edited by 1983hotrod24: 02 March 2010 - 08:30 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Strings and Vectors

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 971
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Strings and Vectors

Posted 02 March 2010 - 08:37 PM

The function is defined as using two arguments:

...
/ Function name     : MessageBox
// Description       : Call MessageBox with message: strMsg,  
//                        caption: strHdg, OK button, and standard style.
// 
//------------------------------------------------------------------------
// 
// Return type                  : int
// Argument                     : const string - the message
// Argument                     : const string - the heading
// 
...
int   MessageBox(const string strMsg, const string strHdr)
{
...



But you are calling it with three:

MessageBox( NULL, L"Lab 2 ", L"This is ");



Don't do that. :) :)

This post belongs in the C and C++ forum, not the "Caffeine Lounge"
Was This Post Helpful? 0
  • +
  • -

#3 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 942
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Strings and Vectors

Posted 02 March 2010 - 09:06 PM

Moving this to the C/C++ forum. You shouldn't post programming questions in the Caffeine Lounge.
Was This Post Helpful? 0
  • +
  • -

#4 1983hotrod24  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 16-January 08

Re: Strings and Vectors

Posted 02 March 2010 - 09:13 PM

You are correct. I knew of this fact, but when I use just two arguements, I receive this error C2665: 'MessageBox' : none of the 2 overloads could convert all the argument types

#include "Util.h"

void WelcomeMessage();
void WelcomeMessageBox();
void main()
{
	int n;
	SetColor();
	clrscr();


	cout << "\n\n\nStarting pt :)/>\n";
	cin >> n;
	MessageBox( NULL, L"Lab 2 ");

	PressAnyKey();
}


Was This Post Helpful? 0
  • +
  • -

#5 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Strings and Vectors

Posted 02 March 2010 - 09:16 PM

One thread per topic is enough. :angry:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1