JMR's

Custom C++ Console App Notes

 

 

............................................. INDEX ................................................

 

Header File Listing Link

cin.getline Note Link

Notes Link

Whatever Link

Web Links To Try Link

Copy and Paste C++ Console Template Source File Link

Code Samples Link

    Using Structures Link

    Inline Exception Throw Link

    Input Fault Tolerance

    Using Files Link

    Source Template Function Link

    Random Number Generation Link

    Convert Integers to Char Array Strings Link

    Passing Arrays To Functions Link

    kbhit Function Link

 

Unknown Things Link

Links To Try For Assistance Link

Links For Knowledge

Class Inheritence
Creating Objects

 

////////////////////////////////////////////// HEADER FILE LISTING //////////////////////////////////////////////////////

Note: You may have to pay attention to the file extension, ie, either use .h or none at all.

         Also, some of these may not like to work with each other.

 

#include <iostream>    // std I / O

#include <string.h>     // to use the string data type

#include <cstdlib>        //

#include <stdlib.h>        //

#include <math.h>        //

#include <ctime>        // for rand num generation seed: srand(time(NULL));

#include <iomanip.h>    // used for setprecision manipulator

#include <stdio.h>        //

#include <fstream>        // used for file I / O

#include <dos.h>        //

#include <algorithm>    // used for transform( a.begin( ),a.end( ), a.begin( ), toupper);

#include <conio.h>        // used for clrscr( )

#include <windows.h>  // used for sleep( ) function

 

Back To Index

 

 

**********  Note on C++ cin.getline / cin.ignore  ************

char someonesName[28] = {' '};

    cout << "Enter Your Name: ";

    cin.getline(someonesName,27,'\n');     // the '\n' does not seem to be needed here

    cin.ignore(80,'\n');                            // the '\n' doesn't seem to be needed here either

 

Adding the '\n's creates a bug somewhat like the one that was in the string.h file.

So use the following:

Note:  If you use cin << whatever before it, it won't wait for the first input

            unless you use cin.ignore(80,'\n');

    char someonesName[28] = {' '};

        cout << "Enter Your Name: ";

        cin.getline(someonesName,27);

*********************************************************

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

NOTES

* Use const in any function parameter that is not going to be changed in the function.

* Use the scope resolution operator for all global variables in class member functions.

* Do not use a statement such as:

                            char myChar = 'A';

 

       unless you are sure that's what you want because, then:

                                if(myChar = = 65)
                                cout << "myChar equals 65."<< endl;

 

       will evaluate to true.

* Clear the buffer after a cin.get ( x );   // (as if you would use one) (don't)

* As best as I recall, long filenames are allowed for openning a file for input

   (and probably output), but my experiments with system( "print file.abc")

    lead me to believe 8.3 format is required with the system( ) command.

* You can only use one .PCH file per source file, but you can use more

    than one .PCH file per project.

* Here are some things to check for when validating numeric data:

        - Floating point numbers

        - Numbers with more than one decimal point

        - A character

        - Characters

        - A string

        - A broken string

        - Negative numbers

        - Numbers that will return incorrect results if out of a certain range

        - The output can be too easily interpreted differently than intended

        - Alphanumerics

        - Out of range for the data types capacity

        - Local variable has the same name as the intended global variable

        - Other (acceptable ?) numeric data types entered, i.e., hex or binary

* You cannot use the typedef specifier in a function.

       

               

 

Back To Index

 

 

------------------------------------ Whatever -----------------------------------

 

fmod(x,y)     // floating point remainder of x / y

abs(x)        // absolute value of  integer x

fabs(x)        // absolute value of the floating-point number x

labs(x)        // absolute value of the long integer x

log(x)        // natural (base e) log of x

log10(x)    // common (base 10) log of x

pow(x,y)    // x raised to the power of y

sqrt(x)        // square root of x

ceil(x) x rounded up to an integer

exp(x)         exponential value of x

floor(x)         // x rounded down to an integer

 

 

new

static

continue;

getline(cin, name);

sleep( 4 );           

system( "color A7");

miles=atoi(num_of_miles);         //converts a string to an integer

miles=atol(num_of_miles); //converts a string to a long integer
miles=atof(num_of_miles); //converts a string to a float

 

// try to compile an  inline function for app speed

    inline  returnType functionName(const int i, bool b, string &someString)   

 

cout<<setw(width)<<"Something to print.";        // doesn't work

virtual                                           // indicates  the base class should only be used once

 

if ( partNumber.size( ) >= 4)

    {            }

transform ( name.begin( ), name.end( ), name.begin( ), tolower);  // do not add arguments

while ( toupper (usersInput) = = 'Y' );

result =  employNum.compare( startCompare, numCharsToCompare, stringTwo );  // returns -1, 0, or 1

location = usersInputString.find( whatToLookFor, startFindAtPosition );    // searchs a string

entry121.replace ( startPosition, numCharsToReplace, "122" ); 

destinationString.assign( sourceString, startPosition, numOfCharsToAssign );

 

 

srand(time(NULL));		// seed the random number generator
num = lowerBound + rand ( ) % ( upperBound - lowerBound + 1);	// generate a random number

 

// setw( x) sets a field width for right-aligning strings for printing to the screen,

//  but numbers will position at the end of the field width and then print.

// Also note that each cout statement needs the function or it will no

// longer apply.

        cout << setw(10) << "Here!" << endl;       

 

// ----  0 is ASCII   #48,  9 is ASCII  #57  ----

 

clrscr( );        // clears the screen, requires conio.h

 

try

throw

catch

goto

typedef            // renames an existing type

_int8                // sized integers

_int16

_int32

_int64

this                // cannot be used outside the body of a class-member function

_outp(port num, info)            // send info byte to port

_outpw(port num, info)         // send info word to port

_outpd(port num, info)          // send info double word to port

union {        };                        // uses one namespace for multiple variables; can be various types

 

// get input
getline(cin,userInput);

// convert to uppercase ( this can be optional )
transform (strUserInput.begin( ),strUserInput.end( ),strUserInput.begin( ),toupper );

exit(int);        // used to exit the program

 

return;        // used to exit the function when desired and no return value is required

return(value or var);  // used to exit the function when a return type is required

 

Back To Index

 

-----------------------------------------------------------------------------------

 

 

 

Links To Try For Assistance

------------------------------------------

------------------------------------------

 

 

 

------------------------------------------

 

Back To Index

 

 

Links For Knowledge

----------------------------------------

----------------------------------------

 

www.swebok.org        // is a link about software engineering

www.contrux.com/survivalguide/        // is a link about software engineering methodology

 

-----------------------------------------

 

Back To Index

 

 

 

CODE SAMPLES

#define    myNumber    1700.5

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

enum sizes {small=5, medium, large};
enum sizes drink_sizes;        // sizes is a type here, and drink_sizes will be a variable of that type
    cout << "small: " << small << endl
    << "medium: " << medium << endl
    << "large: " << large << endl;

 

Back To Index


---------------------------------------------------------------------------------
------------------------------   Using Structures --------------------------------

"A structure can include enumerated data types and even other structures as members.

 

struct Employee
{
char empName[31];
char empSS[25];
float empPayPerHour;
};
 

int main( )

{


Employee *employee_ptr;

employee_ptr = new Employee;

 // for -> to work the structure must be global?
 

strcpy(employee_ptr->empName,"Jim Rhoades");   

strcpy(employee_ptr->empSS, "031-56-1174");
employee_ptr->empPayPerHour = 7.75;
cout << employee_ptr->empName << '\n'
<< employee_ptr->empSS << '\n'
<< employee_ptr->empPayPerHour << '\n';

//now delete the memory allocated with "new "
delete(employee_ptr);

} // end main

 

Back To Index

 

-----------------------------------------------------------------------------------

---------------------------------------- Creating Objects ---------------------------------------

To create an object from a class definition:


	CComputer Computer;

To create an array of objects from a class definition:

	CComputer Computer[5];
	Computer *pComputer = &Computer[0];

To create an object using the "new " keyword:

	CComputer *pComputer = new CComputer;
	
	// be sure to delete the object when done with it
	delete(pComputer);

To create an array of objects using the "new " keyword:

	CComputer *pComputer[5] = new CComputer;    // (I'm guessing this at this time)

	// be sure to delete the array of objects when done with it/them
	delete[](pComputer);



Back To Index

------------------------------------------------------------------------------

------------------------- Inline Exception Throw ---------------------------------

	cout << "Please input a number: ";
		try
		{
			cin >> userNum;
			if(!userNum){
				throw ("Number is required.");
			} // end if
			userNum *= 2;
			cout << "That number doubled is: " << userNum << endl;
			valid = true;
		} // end try
		catch (char *problem)
		{
			cout << problem;
			userNum=0;
		} // end catch
 

Back To Index

---------------------------------------------------------------------	
----- Input Fault Tolerance for Numerical and Character Input -------
--------------------- Using Type char ---------------------------
//AlwaysGetStrings.cpp
//Purpose: Testing out the procedure of always getting
//strings as input for fault-tolerance. (This only works using a char array.)
// (Some of these header files may not be necessary.)

#include <iostream>
#include <string>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;

int main()
{
	//declare vairables
	char num_feet_in_mile[] = "5280";
	char num_of_miles[] = "3";
	char *num_of_miles_ptr = num_of_miles;
	int feetPerMile, miles, totalFeet;


	miles=atoi(num_of_miles);	//converts a string to integer
	feetPerMile=atoi(num_feet_in_mile);
	totalFeet=miles*feetPerMile;
	cout << totalFeet << endl;
			
	//miles=atol(num_of_miles);	//converts a string to a long integer
	//miles=atof(num_of_miles);	//converts a string to a float


	//get user input num of miles
	cout << "Input the number of miles to be traveled: ";
	cin >> *num_of_miles_ptr;

	//should search the string for spaces here
	cout << "\n\n";
	//
	miles=atoi(num_of_miles_ptr);	//converts a string to integer
	totalFeet=miles*feetPerMile;
	cout << totalFeet << endl;
	cout << "\n\n";

	return(0);
} // end of main function

Back To Index

 
---------------------------------------------------------------------------------
-------------------------- File Using ----------------------
 
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
 
int main( )
{
 
ofstream outFile;			// declare file pointer for output file
outFile.open("outputFile.dat", ios::app");	  // ios::out would open the file for output (overwrites )
ifstream inFile;			// declare file pointer for input file
inFile.open("inputFile.dat", ios::in");	
 
// another possibility for the following line is:
	// if (outFile.is_open())
if (outFile)
{
	outFile << "Some output" << endl;
}
// what about a check for inFile.is_open() ????
if (!inFile.eof( ))
{
	//-------- use this if not delimited ( use if all on individual lines ) ---------
	inFile >> someInput;
	inFile >> ssNum;	
	// ------------- or maybe this, using # (octothorp) as a delimiter -----------
	getline(inFile, someInput , ' # ');
	inFile >> ssNum;
	inFile.ignore(1,' \n ');
}
 
someFunction (outFile, inFile);		// call function, pass file object pointers
outFile.close( );
inFile.close( );
} // end main
 
someFunction (ofstream &outFileName, ifstream &inFileName)
{
	// do some file actions
}// end someFunction
 
 

Back To Index

 
---------------------------------------------------------------------------------
-------------------------- Source Template Function ---------------------------
template <class T>
T reverse(T value);
 
int main( )
{
	int valOne = 10;
	float valReturned = float(0.0);
	cout << "valOne before template function call: " << valOne;
	cout << endl << endl;
	valReturned=reverse<int>(valOne);
	cout << "valOne after template function call\n" 
		 << "with an explicit type cast: " << valReturned;
	cout << endl << endl;
	valReturned=reverse(valOne);
} // end main
 
 
template <class T>
// T stands for any type -- simple or programmer-defined
T reverse(T value)
{
	return(-value);
} // end reverse template function

Back To Index

 
-------------------------------------------------------------------------------------------
--------------------- Random Number Generation ----------------------------------
 
#include <ctime>
#include <math.h>
 
int main ( )
{
	srand(time(NULL));		// seed the random number generator
	//  now generate a random number
	num = lowerBound + rand ( ) % ( upperBound - lowerBound + 1);
	cout << "The Random Number Is: " << num << endl;
 
} // end main

Back To Index

 

-------------------------------------------------------------------------------------------
----------------- Convert Integers To Char Array Strings ----------------------
 

(header files)

 

int main( )

{

int one = 12, two = 747;

string myString = "";
string secString = "";


itoa(one, chOneArray, BASEOFNUMBERSYSTEM); // convert integer one into a string
itoa(two, chTwoArray, BASEOFNUMBERSYSTEM); // convert integer two into a string

// NOTE: ONLY USING THE  CHAR ARRAY ARGUMENT

    // (one of the three possible / required? arguments)!
myString.assign(chOneArray);         // assigning a char array to a string variable
myString += " ";
// NOTE: ONLY USING THE CHAR ARRAY ARGUMENT!

    // (one of the three possible / required? arguments)!
myString += secString.assign(chTwoArray);         // assigning a char array to a string



// string printing
cout << setw(10) << myString << endl;
// the integers will not be in the alignment field
// char printing
cout << setw(10) << chOneArray << " " <<chTwoArray << endl;
// the integers will not be in the alignment field
// number printing
cout << setw(10) << one << " " << two << endl;
// text string printing
cout << setw(10) << "Here!" << endl; // will right align in 10 char field
// so only "strings" will be in alignment fields, numbers to the right of the field?
 

// SEEMS THERE'S NO NEED TO UNSET THE PRINT FIELD WIDTH

 

return(0);

 

 

}// end main

Back To Index

 

-------------------------------------------------------------------------------------------
--------------------- Passing Arrays To Functions ----------------------------
 


// function prototype
float calcTotal ( float [] );
int main ( )
{
    // declare variables
    rainfall [12] = {0.0};
    // call function, pass array
    calcTotal( rainfall );

} // end main

float calcTotal( float  r[ ] )
{ 
  // do whatever
} // end calcTotal

Back To Index

 

-------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------
---------------------------------- Class Inheritence -------------------------

Generally, the new class uses the old class, and therefore inherits from it.
The new class is named on the left, followed by the class(es) it inherits from
(ie, put the old class into the new class).
Also note that the base class must use protected instead of private if you want to
use the members of that section.


class CComputerWithCD_ROM : public CComputerWithPrinter, public CBaseComputer
{
protected:

public:

};

Back To Index

-------------------------------------------------------------------------------------------

--------------------------------- kbhit function --------------------------------------
 

Example

/* KBHIT.C: This program loops until the user
 * presses a key. If _kbhit returns nonzero, a
 * keystroke is waiting in the buffer. The program
 * can call _getch or _getche to get the keystroke.
 */

#include <conio.h>
#include <stdio.h>

void main( void )
{
   /* Display message until key is pressed. */
   while( !_kbhit() )
      _cputs( "Hit me!! " );

   /* Use _getch to throw key away. */
   printf( "\nKey struck was '%c'\n", _getch() );
   _getch();
}

Output

Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!!
Key struck was 'q' 



Back To Index

-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
 

 

 

-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
 

 

 

-------------------------------------------------------------------------------------------
------------------------------------ Unknown Things --------------------------------------
Keywords:

asm                        // how to implement ?

mutable                    // ??

register                    // access the registers ?

static_cast            // type-cast as static ??

typeid                    // ??

typename                // ??

volatile                    // no longer static ??

wchar_t                // ??

sizeof                    // size of an array, ie, number of elements ?

explicit                   // ??

extern                    // variable is declared in another...?

const_cast            // type-cast as const ??

dynamic_cast        // type-cast as regular variable ??

this                        // refers to ... object ?

 

            //  isn't there a  round( ) function ??

 

and_eq            // and equal ?                                    , just a #define

bitand                // how to use ?        &   operator ,  just a #define

bitor                // how to use?            |   operator , just a #define

compl                // complement ?         ~ operator ?

not_eq            // not equal ?                                            , just a #define

or                    // like ||  ??                                             , just a #define

or_eq                // or equal ??                                        , just a #define

overload            // like     function operator + (  )  ??

xor                    // exclusive or                                        , just a #define

xor_eq                    // exclusive or equals ??                    , just a #define

not                            / ! operator ??

state_cast            // ??   

friend                        // how to use properly?

auto                     // ??

reinterpret_cast        // ??

^                          // operator  ,  what does it do ?

,                            // sequencial evaluation   ,  how to use it ?

<<                    // shift operator , how to use ?   (something like multiplying or dividing by 2)

>>                    // shift operator, how to use ?

 

 

Back To Index

 

-------------------------------------------------------------------------------------------