Wavelength Logo
tl.jpg (2351 bytes) blank.gif (837 bytes) tr.jpg (2446 bytes)
blank.gif (837 bytes)
C++ Review by Erik Corradino
blank.gif (837 bytes)
C++ Cheat Sheet by Erik Corradino part 1 of 3

Keywords For C/C++: One of a list of special words of significance to the C++ compiler.

auto
continue C/C++/Java and unrealscript same exact thing
enum
if C/C++/Java and unrealscript same exact thing!
short
switch C/C++/Java and unrealscript same exact thing
case C/C++/Java and unrealscript same exact thing
volatile
break
default
extern
sizeof
union
struct
class C++/Java and unrealscript same exact thing
register
static
unsigned
const C/C++/Java and unrealscript same exact thing
if C/C++/Java and unrealscript same exact thing
else C/C++/Java and unrealscript same exact thing
typedef
do while loop C/C++/Java and unrealscript same exact thing
while C/C++/Java and unrealscript same exact thing
do C/C++/Java and unrealscript same exact thing
for C/C++/Java and unrealscript same exact thing
goto Do not use!
Return C/C++/Java and unrealscript same exact thing
void
malloc Use new and delete instead of malloc.
C++
asm
delete
new
inline Use instead of macros.
private
static_cast
try
catch
throw
wchar_t
bool
dynamic_cast
mutable
protected C++/Java and same exact thing
private C++/Java and same exact thing
public C++/Java and same exact thing
template
typeid
explicit
this
namespace
typename
false
new
reinterpet_cast
using
const_cast
friend C++/Java and same exact thing
operator
true
virtual Not sure if in unrealscript or java.




Data Types:
Declaration name Data type Range
char character -128 to 127
unsigned char unsigned character 0 to 255
signed char signed character (same as char) -128 to 127
int integer -32,768 to 32767
unsigned int unsigned integer 65,535
signed int signed integer -32,768 to 32767
short int short integer -32,768 to 32767
unsigned short int unsigned short interger 65,535
signed short int signed short interger (same as short int) -32,768 to 32767
long long interger -2,147,483,648 to 2,147,483,647
long int long integer same as above
signed long int signed long integer same as above
float floating-point (real) decimal math -3.4e38 to 3.4e+38
double double floating-point -1.7e 308 to 1.7 +308
long double long double floating point (real) -3.4e4932 to 1.1e+4932




Escape Sequences:
\a Alarm
\b Backspace
\f Form feed (New page on printer
\n New line
\r Return carriage
\t Tab key
\v Vertical tab
\\ Backslash (\)
\? Question mark
\' Single quotation
\" Double quotation
\000 Octal number
\xhh Hexadecimal number
\0 Terminator ( null)




Operators:


:: Scope access

() Function call

[] Array subscript

-> Indirect component selector

. Direct component selector

Unary

! Logical negation

~ Bitwise (1's) complement

+ Unary plus

- Unary minus

& Address of (references)

* Indirection (pointers)

sizeof Returns size of operand in bytes

new Dynamically allocates C++ storage

delete Dynamically deallocates C++ storage

type Typecast

Member access

.* Dereference

-> Dereference

() Expression parentheses

Math

* Multiply

/ Divide

% Remainder (Modulus)

+ Add

- Subtract

++ Increment

-- Decrement

Shift keys

<< Left shift

>> Right shift

Relational operators

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

Equality operators:

== Equal to

!= Not equal to

Bitwise:

& AND

^ XOR

! upside down ! Bitwise OR

Logical:

&& Logical AND

!! Logical OR

Ternary:

? : Conditional Assignment

Assignment operators:

= Simple Assignment

*= Compound Assignment Multiply

/= Compound Assignment Quotient

%= Compound Assignment Remainder

+= Compound Assignment Sum

-= Compound Assignment Difference

&= Compound Assignment Bitwise AND

^= Compound Assignment Bitwise XOR

!= Compound Assignment Bitwise OR

<<= Compound Assignment Left Shift

=>> Compound Assignment Right Shift
Note: Bitwise operators are very rarely used unless one is a assembly guru.

C++ stream library

cout and cin: cout and cin are for input and output streams (iostream).

Example:

cout << "hello!";
cin >> name; // user input


ifstream
ofstream
fstream

identifier meaning
ios::app Open stream to append data
ios::ate Set stream pointer to end of file
ios::binary Open in binary mode
ios::in Open stream for input
ios::nocreate Generate an error if the file does not already exist
ios::noreplace Generate an error if the file already exists
ios::out Open stream for output
ios::trunc Truncate the file size to 0 if it already exists

"Works Cited"

C++: How to program by Deitel and Deitel

C++ Primer by Stanley Lippman

C++ Primer Answer Book by Clovis Tondo

C++ in 21 Days by Jesse Liberty

C++ for Dummies (Quick Reference) by Namir Shammas

All books are available at Amazon.com.

Books I heard were good but have not read yet:

Java in a Nutshell

1001 Java Programmer Tips

Core Java Fundamentals

Design Patterns

The C++ Programming Language

//=====================================================


part2



C++ Glossary by Erik Corradino

Class: A special user defined type that represents data and functions that operate on that data, for a category of objects. Classes have data members and member functions.

Base class or Super class: A class that is not a descendant of a class.

Derived class, Child class or subclass: A class that is a descendant of another class.

Object: An instance of a class.

Constructor: A special member function that initializes a class instance. There are three types of constructors: default, copy and custom.

Data member: Members of a class that store attributes of an object.

Data type: A type/kind of information.

Destructor: A special member function that is automatically invoked to remove a class instance.

Member function: A member of a class that supports an operation on that class.

Parameter: A special variable that passes information to and from a function or a member function.

Argument: The value that is assigned to a parameter.

Iterator: A loop; A program part that enables you to repeat one or more tasks. For, do-while and while are three types of iterators.

Recursive functions: A function that calls itself. (Recursion can get very complex with numbers.)

Structure: A user defined type that stores data members but no member functions. Each data member has its own type.

Union: A user defined type that has data members occupy the same memory space (sharing).

Constant: A name that is associated with a value that is fixed.

Variable: A name that is associated with a value that can change.

Expression: A collection of operators and values that yields a single result.

Switch statement: A decision making statement that supports multiple alternatives.

Comments: Notes in the code that the compiler ignores.

// this is a comment that ends at the end of the line

/*
this is also a comment
that blocks out code
*/

Tip: Use comments liberally! To make your code easier to maintain.

Arrays: Arrays are special variables that store multiple values of a single type.

Element of Arrays: A slot in an array.

Pointers: A special variable that stores the memory address of another variable or object. UnrealScript and Java are pointerless.

Compound types: Arrays, vectors, references and pointers are compound types.

Typecasting: Converting a data type.

Virtual Member Function: A member function that has the same parameter list as the ones in parent and or descendant classes. Virtual member functions support consistent response in class hierarchies.

Void Constructor: A constructor that has no parameters or with parameters that only have default arguments.

String: A set of characters, either numbers or letters or symbols.

Stream: Flow of data, either input or being output.

Template Class: A class that works with many data types.

Template Function: Functions that work with one or more data types.

Function: The major block of a program. Inside these {} is what the program does!

Debugging: The process of finding and fixing errors.

Address: The location of an object in memory.

Compiler Directive: # Gives an instruction to the compiler.

Data Object: A place in memory to store a value of a type. Usually have a name, value, type and address.

Expression: The main unit of computation in C++.

rvalue: The name of an object when it is used.

Algorithm: A defined sequence of steps for solving problems.

Library: A collection of code.

Actual Argument: Argument in a function call.

Automatic: An object defined in a block whose life extends at the end of the block.

Declaration: The introduction of an identifier into a program.

Definition: A declaration that tells the meaning of the identifier.

Function Declaration: A listing of function by return type, name and formal argument list.

Function Definition: A declaration of a function that includes the function body.

Global: Not used in OOP. Declarations that are made outside any block.

Pass By Reference Argument: A formal argument that serves as a name for an actual argument during the execution of the function.

Pass By Value Argument: A formal argument that is created and initialized by the value of the actual argument when execution of the function begins.

Precondition Of A Function: An assumption that the function makes about its actual arguments.

Procedure: A void function.

Signature: A function prototype that does not include names for the formal arguments.

Void Formal Argument List: An empty argument list, symbolized by () or (void) to show the function has no arguments.

Void Function: A function that does not return a value.

Function Call: The act of invoking a function.

Function Overloading: Using the same name to declare multiple functions.

Polymorphism: Objects of different classes that are related respond in a different way to the same message (function calls).

Boolean Expression: An expression whose value can be interpreted as true or false.

Typedef: A language feature for giving a new name to an existing type.

Driver: A program written to test a function.

Conditional operator: The ternary operator ? :. The expression a? b :c evaluates to b if a is true and to c if a is not true.

Demorgan's Laws: Two rules indicating how to distribute ! over && and ||. !(a&&b) is equal to !a||!b and !(a||b) is equivalent to !a&&!b.

Enumeration Type: A programmer defined integer type (constant).

Logical AND: The operator &&. A&&B is true if both operands are true, if not it is false.

Logical Negation: The operator !. !A is false. If A is true and true if A is false.

Logical OR: The operator ||. A||B is false if both operands are false and it is true otherwise.

Short-circuit Evaluation: Partial evaluation of a boolean expression. In a&&b, if a is false, b is not evaluated (the value of the expression is false) In a||b, if a is true, b is not evaluated (the value of the expression is true).

if/else: If statements test operators. Else statements tell the program what to do when an if statement is false.

If/else syntax:

if(condition)
statement true
else
statement false

If example:

float taxs(float salary)
{
float tax = .0;
if(salary >= 50000)
tax = salary * . 03;
return tax;
}

If/else example:

main()
{
int credits;
cout << " how many college credits do u have?";
cin >> credits;
if(credits < =30)
{
cout << " You are a freshman.";
}
else
{
cout << thank God u r not a freshman.";
}
}
//===========================================

Switch: Statements which search a number of possible answers for a matching answer. Once a break is found, the program stops searching for matching answers.

Switch example:

void main()
{
int height;
cout << "how tall are you in inches?";
cin >> height;
switch (height)
{
case ('66'):
{
cout << "You are 66 inches tall.";
break;
}
case ('70'):
{
cout << " You are 70 inches tall.";
break;
}
default:
{
cout << " You are not tall.";
}
}
}
//===========================================

Iterators (Loops): Repeated execution of the same set of programming instructions. To stop the repeat, a condition must be met, or it will loop forever. There are three types of loops: while, do-while and the for loop.

While loop: Uses relationships to stop from looping. Once the relationship is false, the loop is ended. While loops test at the beginning of the loop.

While example:

int count = 0;
while (count < 50)
{
cout << "hello world" << endl;
count++; // postfix incrementer
}

Do-while loop: This loop will be executed at least once. The do-while loop tests its condition at the end of the loop.

Do-while example:

void main()
{
float weight;
do
{
cout << " how much do u weigh?";
cin >> weight;
if ((age < 14)||(age > 16))
{
cout << " You cannot be that big" << endl;
cout << "tell me the facts << endl;
}
while ((age < 14)||(age > 16));
if (weight < 200)
{
cout << You must lift weights.";
else
{
cout $lt;< " wow u r big.":
}
return 0;
}
//================================================

For loop: To control a single for loop the programmer needs 3 values.

For loop syntax:

for (1stexpression; conditional; countexpression)
{
// function block here
}

For loop example:

for (up = 40; up >= 4; up--)
{
cout << up << endl;
}

Break Command: Break commands will stop a loop before it would normally end. Break commands only work on loops and switch statements.

Return Command: Stops a function before it would end.

Continue command: Opposite of the break command, continue repeats the loop once it has finished.

Continue example:

for(up=0; up > 10; up++)
{
cout << "jane" << endl;
continue;
cout << " doe" << endl;
}

Struct: User defined data type which only holds data members not member functions!

Struct example:

struct date
{
int day;
int month;
int year;
};

Classes: Holds data members and member functions!

Class date
{
public:
// constructor
date(int d, int m, int y);
// d = day
// m = month
// y = year

// functions to access data indiviually
int day() const;
int month() const;
int year() const;

void advancedate(); //changes dates

protected:
// data
int day_;
int month_;
int year_;
};

Scope Resolution Operator: Designates the class to which the function belongs.

Scope Resolution Operator example:

classname :: memberfunctionname

Private: Access specification for a class member. Only class members have access to private members of the class.

Public: Access specification for a class member. Public members can be accessed by any code.

Protected: Access control allowing member access for the declaring base class, its friends and its derived classes and their friends but not outside the class hiearchy.

Protected Inheritance: Inheritance in which public and protect members of a base class are considered protected members of the derived class.

Public Inheritance: Inheritance in which public members of the base class are public members of the derived class and protected members of the base class are protected members of the derived class.

Private Inheritance: Inheritance in which public and protected members of a base class are considered private members of the derived class.

Polymorphism: Using the same syntax to do different things depending on the context.

Runtime Polymorphism: The ability of a pointer to a base class type to cause invoking of different functions and pointers or references.

Virtual functions: A functions in a base class declared with the keyword virtual. Virtual functions can be overridden in derived classses.

Overriding: Definition of a function in a derived class declared as a virtual function in a base class. The definition of a function in a derived class with the same name as a nonvirtual functions in the base class is hiding.





Functions: All programs have the main() function. All functions perform tasks (decision making; if/else/switch or looping for/do/while etc…). The return keyword enables the program to exit the function. Void functions do not return values.

Actual argument: Argument in a function call.

Automatic: An object defined in a block whose life extends at the end of the block.

Declaration: the introduction of an identifier into a program.

Definition: A declaration that tells the meaning of the identifier.

Function Declaration: A listing of function by return type, name and formal argument list.

Function Definition: A declaration of a function that includes the function body.

Void Function: A function that does not return a value.

Function Call: The act of invoking a function.

Function Overloading: Using the same name to declare multiple functions.

Default Arguments: Rules when assigning default arguments to a parameter: After the first default arguement, you must assign default arguments to all subsequent parameters. One may assign default arguments to any or all parameters as long as you obey the above rule. Default arguments divide the parameter list of a functions into 2 parts: The first part contains parameters with no default arguments. The second part contains parameters with default arguments. When using a default argument of a parameter, omit the argument for that parameter in a function call. To use a default argument for a parameter, one muse use the default arguments for all the subsequent parameters. You cannot pick and choose. The compiler cannot think and is unable to know which argument belongs to which parameter.

Inline Function: The inline function replaces the calls to that inline function with its statement. The compiler also replaces the functions parameters with its arguments.

Inline Function syntax:

inline returnavalue functionname(parameters here)
{
return expression;
}

Function Overloading: Enables one to declare functions that have the same name but different parameter lists.

Function Overloading example:

double mysize(double myheight, double myweight);
double mysize(double myheart, int mycompassion, int mycaring);
double mysize(double mymuscles, double mystrength, int myendurance);

Tips for overloading functions:
Each version of the overloaded function must have a different functions signature, or it is called function overriding! The signature of the function is defined by the number or parameters and their data types. This signature does not include its return type, because C++ enables you to ignore the return type in a statement. The signature of a function does include the sequence of parameters that have different data types.
Functions that have parameters with default arguments, the compiler does not include these parameters as part of the functions signature.






Constructors: Special members that initialize class instances. The compiler generates code that automatically invokes an appropriate constructor when your create a class instance.

Constructor syntax:

Class classname
{
public:
// void constructor
classname();
copy constructor
classname (classname& classnameobject);

// additional constructor
classname (parameterlist);

// data members and member functions here
};
//================================================

Destructors: Members that uninitialize class instances when they reach the end of their scope.

Destructor syntax:

class yourclassnamehere
{
public:
//void constructor
classname();

// destructor
~classname();

//other members here
};
//================================================





Inheritance:

Inheritance examples:

Class superclass
{
public:
foo(int);
// stuff here

protected:
int_bar;
double_foo_bar;
};

class subclass : public superclass
{
public:
foo(string);
bool bar(base *pb);
void foobar();
// data members and member funct here

protected:
string_bar;
};
//================================================





Friends: The friend keyword mechanism allows a class to grant functions access to its non-public members. This keyword should be used within a class definition.

Class window
{
friend istream& operator>>(istream& window&);
friend ostream& operator << (ostream& const window&);
public:
// the rest of the window class here
};
//================================================





Arrays: A defined number of memory slots for a variable's values. Observe these rules for arrays:
List of initial values appears in a pair of braces and is
comma delimited. The list ends with a closing brace followed by a semicolon.
The list may contain a number of initial values that are equal to or less than the number of elements in the initialized array. Otherwise, the compiler generates a compile time error.
The compiler assigns the first initializing value to the element at index 0, the second value is 1 and so on.
If the list contains fewer values that the number of elements in the array the compiler assigns zeros to the elements that have no value.
If you omit the number of array elements, the compiler uses the number of initializing values in the list as the number of array elements.


Array syntax:

type arraynamehere[numberofelements] = {value0...,valueN};

Array example:

char Yournamehere[15];
Yournamehere = "johncarmack";

When the array is placed in memory it looks like this:
[0] j
[1] o
[2] h
[3] n
[4] c
[5] a
[6] r
[7] m
[8] a
[9] c
[10] k
[11]
[12]
[13]
[14]

Note: Arrays start at zero!

Dynamic Arrays: Dynamic arrays are arrays that one can create and remove at runtime. C++ offers the keywords new and delete to create and remove dynamic arrays.

Dynamic Array syntax:

pointertomyarray = new datatype[numberofelements];

Multi-dimensional Arrays: Arrays that have two or more dimensions. After you declare a multidimensional array, you access its elements by using the index operator [].

Multi-dimensional Array syntax:

myarrayname[indexofdimensions1][indexofdimensions2]..

Multi-dimensional Array example:

const int max_rows =20;
const int max_cols = 40;
// max_rows and max_cols are constants
double fMatrix{max_rows] {max_cols];
for(int I=0; I < max_rows; I++)
for (int j=0; j < max_cols; j++)
fMatrix[I][j]=double(2+I 2*j);
//==================================================





References: References are used as formal parameters to a function, and to pass class objects into a function. A reference type is defined by following the type specifier with the address of operator.

int ival=1024;
// ok refval is a reference to ival
int &refval=ival;
// error: a reference must be initialized to an object.
tnt &refval2;

References are a "type" of pointer; do not initialize it to the address of an object, as we would a pointer.

int ival =1024;
// error: refval is of type int, not int*
int &refval =&ival;
int *pi + &ival;
// ok: refptr is a reference to a pointer
int *&ptrval2 =pi;

References cannot be resigned or cannot be made to refer to another object. You must initialize it.

//===================================================





Standard Exceptions:

Exception Class Parent Class Purpose
exception none The base class for all the exceptions thrown by the C++ Standard library.
logic_error Exception Reports Logical program errors that can detect before the program proceeds to execute subsequent statements.
Runtime_error Exception Reports runtime errors that are detected when the program executes certain statements.
ios::failure Exception Reports stream i/o errors.
domain_error logic_error Report infraction of a condition.
invalid_argument logic_error Signals that the argument of a function is not valid.
length_error logic_error Signals that an operation attempts to create an object with a length that exceeds or is equal to npos (the largest value of the type size_t).
out_of_range logic_error Signals that an argument is out of range.
bad_cast logic_error Reports an invalid dynamic cast expression during runtime identification.
Bad_typeid logic_error Reports a null pointer in a type identifying expression.
Range_error runtime_error Signals invalid postcondition.
overflow_error runtime_error Signals arithmetic overflow
bad_alloc runtime_error Signals the failure of dynamic allocation.

Throwing Exceptions:

class badvalueexception
{
public:
badvalueexception(int nval=0;)
{
cout << nval << " is a bad value\n";}
};

int nbadval;
throw badvalueexception(100);
throw nbadval;
//===================================================

Try Block: throwing exceptions occur in the try block.

Class badvalueexception
{
public: badvalueexception(int nval=0;)
{cout << nval$lt;< "is a bad value\n";}
};

main()
{
int nbadval;
try{
throw badvalueexception(100);
}
return 0;
}
//===================================================

Catch Clauses: Catch clauses have logic that is similar to that of the case clauses of a switch statement.

Catch Clause syntax:

catch(exceptiontype[exceptionobject])
{
// statements that rethrow exception here
}
//===================================================


//====================================================


part 3



C++ Headers by Erik Corradino

Note: All code is sample code, and is untested as I do not have the time. It is for understanding concepts only. If I left anything out or if there are any typos let me know (I wrote it at night), by email at: corradino@fau.campuscwix.net.

All functions for a class must have a definition. Definitions are sometimes called function implementations. Defining class functions (called methods or member functions), one must have a function header and a function body. It is good programming practice to put member variable declarations and member function definitions in a header file with your class declaration. Function definitions (or implementations) for that class go in the accompanying source file.

The easiest way to use header files is to collect a group of declarations from several cpp files and have them all share that header file by including it (#include namegoshere). The files that have the definitions of the procedures can be compiled separately. Header files are all suffixed with .h or .hp or .hpp. Example: dog.h or dog.hp or dog.hpp. Header files can also be used by introducing 2 files for each program fragment - one header and the other containing definitions. This is code reuse. Any file can be used by another including its header.

Quickie example: Put the declaration of your class, Barneythedino.hpp and your class methods into a file called Barneythedino.cpp , put this code at the top of the .cpp:
#include barneythedino.hpp

Declaring a class tells the compiler what a class is - its data members and member functions. The declaration of a class is the interface - why? It tells the programmer how to interact with the class that is declared in the header file. The functions definition tells the compiler how functions work.

Functions definitions are called implementations of the class methods (class functions) and are inside the cpp file. Implementation details of a class are of concern to the programmer/creator of the class. Clients of a class - (Part of the program that use the class) do not care how functions are implemented.

Note: Header files are not compiled! .c .cp .cpp and .cxx files are compiled. Programmers create custom header files.

Examples:


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

/***********************************************************
Author: Erik Corradino
Date: 2/25/99
Time: 10:30 am
Environment: MSVC++ version 5 and MS word 7
Purpose: tutorial
Filename: dopefish
*********************************************************/

//dopefish.hpp put a ton of comments in this code!

#include // new ansi/iso is
// # include is a compiler directive that instructs the compiler
// to read your code.

using namespace std;

class dopefish
{
public:
dopefish (int Initial Weight); // constructor
~dopefish(); // destructor
int GetWeight() { return itsWeight; } // inline!
void SetWeight (int Weight) { itsWeight = Weight; } // inline
void Ilovedoomandquake()
{
cout << "I love doom and quake.\n";
}

private:
int itsWeight;
};

// end of hpp file
//===================================


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

//dopefish.cpp

// inline function demo
// and use of header files

#include "dopefish.hpp"
using namespace std;
// always include header files

dopefish::dopefish(int initialWeight)
{
itsWeight =initialWeight;
} // constructor

dopefish::~dopefish() // destructor
// takes no action


// dopefish_program.cpp
// create a dopefish
//set its weight and cout
int main() // or int main (void)
{
dopefish commanderkeen(160);
commanderkeen.ilovedoomandquake();
cout << "I love doom and quake\n";
cout << " commanderkeen.getweight() << "lbs.\n";
commanderkeen.ilovedoomandquake();
commanderkeen.SetWeight(180);
cout << " now commanderkeen is\n";
cout << commanderkeen.GetWeight() << "lbs.\n";
return 0;
}
//==============================================


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

Another example with the stack data structure (last in first out!):


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

//============================================
// Stack.hpp
class Stack
{
public:
Stack(int sz = 5); // constructor
void Push(char item);
char Pop();
void Print();
int IsEmpty();
int IsFull();

private:
int maxstack;
int top;
char *entry;
};

// end of stack.hpp file
//================================================


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

// Stack.cpp file

#include
#include "Stack.h"
using namespace std;

void Error(char *);

// stack: constructor for a stack object
Stack::Stack(int sz)
{
maxstack =sz;
top =0;
entry = new char [maxstack];
}

// Push: push an item onto the stack
void Stack::Push (char item)
{
if (IsFull())
Error ("stack overflow");
else
entry[top++] = item;
}

// Pop: pop an item from the stack
char Stack:: Pop()
{
if(IsEmpty())
Error ("stack underflow");
return entry[--top];
}

// print: print a stack from top to bottom
void Stack::Print()
{
for (int i = top - 1; i>=0; i --)
{
cout << ' ' << entry[i];
cout << '\n';
}
}

int Stack::IsEmpty()
{
return top <=0;
}

int Stack::IsFull()
{
return top >= maxstack;
}
// end of stack.cpp file
//--------------------------------------------------------------------


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

// main.cpp file

#include // or // different compilers are different
#include
#include "Stack.h"

using namespace std;

// main: test the stack program
int main()
{
Stack stack(3);
char item;
while (cin >> item)
{
switch(item)
{
case 'a':
cin >> item;
stack.Push(item);
break;
case 'd':
cout << stack.Pop() << '\n';
break;
case 'p':
stack.Print();
break;
case 'q':
return 0;
case ' ':
case '\t':
case '\n':
break;
default:
cerr << "Unknown command: <" << item << 'n';
break;
}
}
return 0;
}

// Error: Print error message and exit
void Error(char *message)
{
cerr << "Error :" << message << '\n';
exit (1);
}
// end of code examples
//==============================================
 

 

blank.gif (837 bytes)
bl.jpg (2471 bytes) blank.gif (837 bytes) br.jpg (2132 bytes)