[Skip Navigation] [CSUSB] / [CNS] / [CSE] / [R J Botting] / [CSci202] / resources
[Text Version] [Syllabus] [Schedule] [Glossary] [Resources] [Grading] [Contact] [Question] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Thu Aug 25 21:09:16 PDT 2011
Opening the PDF files on this page may require you to download Adobe Reader or an equivalent viewer (GhostScript).



      Come and see a Professor in his natural habitat


      Feeding time is normally 11:15-11:45 in JBH309.

      I don't bite.... [ calendar.html ]

      And if I'm not in, check any nearby open door... we all know C++ and most of us like to help you solve problem. We all enjoy sorting out confusing error messages....

      Bring a printout of the code and the evidence of a problem!

      Example of C++ Code for CSci202 and CSci201

      An archive of C++ examples: [ examples ]


      [ Subjects.html ]

      Computer Science Club

      [ http://club.csci.csusb.edu/ ]


      [ http://www.userfriendly.org/ ] [ jokes.txt ]


      [ functions.html ]


      The CS201 introduction to strings [ ../cs201/string.html ]

      A list of string handling functions in Standard C++: [ string ] also see stringstreams.


      [ typedef.html ]

      Input, output, Files, and Streams

        Design programs as filters if you can

        If your program reads cin and write cout and does not prompt the user then you can make it work, after compilation, by redirection
         		./example <input >output

        Do this if possible!

        Theory of files and streams

        The operating system has a name for files complete with an extension and space characters. This name does not fit the naming rules for identifiers in a programming language. So it makes sense that the program has an internal and temporary name that is attached to files. These have type "stream". You have already met the standard input and output streams <iostream> cin and cout.

        The good news is that all input streams work like cin and all output streams like cout. All you need to learn is how to connect a stream to a file.

        Here is the pattern for using a file

        1. Open the file.
        2. Check the file was there.
        3. Work on the file.
        4. Close the file.

        You must not omit the first and last steps above.

        Include <fstream>

        If you want to access files you will need to put
         		#include <fstream>

        Declaring file streams

         		ifstream input;
         		ofstream output;
         		fstream input_and_output;  //but not both at once

        Opening files

        All files have to be opened -- and in the case of fstreams you must say if it is for input or for output. If the file name is in character string literal this is easy:
         		input_and_output.open("Name_of_file", ios::in); //for reading
         		input_and_output.open("Name_of_file", ios::out); // for writing

        If the name of the file is in a string variable then you have to add ".data()" to it to extract the oldfashoined "char*" inside.

         		input_and_output.open(Name_of_file_as_string.data(), ios::in);
         		input_and_output.open(Name_of_file_as_string.data(), ios::out);

        Closing files

        All files should be closed

        Reading A File

        The file must be opened for input
         		input >> variable ....;
        inputs data upto the next space or end-of-line. Spaces are not skipped.
        Inputs the next character -- including spaces and end-of-line characters.
         		getline(input, string_variable);
        Input the next line (including white space but not the end-of-line.

        Writing to a file

        The file must be open for output.
         		output << expression <<...
        Evaluates the expresssion and outputs the value. You can also control the formatting of the output using the <iomanip> library.

        Examples of code

        1. Hello World Revisited writing and reading a file: [ hello.cpp ]
        2. Using getline: [ Hello.cpp ]
        3. Copy one file to another [ copy.cpp ]
        4. Read a line of characters, one by one, from a line: [ charlene.cpp ] (no spaces), [ charline.cpp ] (cool).
        5. Using >> with open+close: [ fq.cpp ] (Note use of read ahead and diagnosing a missing file)
        6. All Known formatting functions and manipulators: [ formats.cpp ] [ iomanip.cpp ]
        7. IO States [ iostates.cpp ]
        8. Random Access Files [ t10.4.cpp ]

        . . . . . . . . . ( end of section Examples of code) <<Contents | End>> Older Examples of code:

        1. All Known formatting functions and manipulators: [ formats.cpp ] [ iomanip.cpp ]
        2. IO States [ iostates.cpp ]
        3. Read a line of characters, one by one: [ charlene.cc ] [ charline.cc ]
        4. Using getline: [ Hello.cpp ]
        5. Skip to end of line [ skipnwln.cc ]
        6. File I/O and encryption [ encrypt.cc ]
        7. Using >> with open+close: [ fq.cc ]
        8. Payroll program [ payroll.cc ] + [ prcsemp1.cc ]
        9. Hello World Revisited [ hello.cpp ] [ Hello.cpp ]
        10. Random Access Files [ t10.4.cpp ]

        Documentation on fstream: [ iomanip.html ]

        Input/Output Manipulators

        [ iomanip.html ]


        In our older(1997) C++ system(Gnu C++ vn 2.8.1) these are called 'strstreams'. The book uses the ANSI/ISO standard library that is becoming available on more and more C++ systems.

        (strstream): vs
        (stringstream): [ tss.cpp ]

      . . . . . . . . . ( end of section Input, output, Files, and Streams) <<Contents | End>>

      Simple Project File

      Use this [ project.cpp ] as a skeleton file to start your pjects -- fill in the blanks.

      Complex Projects

        Organizing a complex project into modules takes time and planning. Doing it in the standard way can save much time and worry as things change.

        The UML Component diagram is a way to think out, record, and present to others your plans for breaking a program into modules.



          A module is a piece of a program that can be compiled independently of the rest of the program that uses it. One module is used by more than one program. These other programs must know how to access the module. They shouldn't have to recompile it. They don't need to be ware of the details of what is inside the module. So it is normal to split a program up and only have to recompile one piece at a time.

          For example think about the <math> library: you want to know how to use parts of it but not how it is programmed. The sqrt function does square roots for you without you knowing how it does it. Similarly, we can use strings, vectors, and streams and ignore the work done to make them work correctly. Most programmers need to know how use a module but don't have the time to worry about how the module actually works. In other words a module has two views. This is like a pet owners view of a cat:

          • Owner's view
          • purr stroke()
          • ...
          vs the view that a veterinarian takes of the same cat on an Xray machine:
          1. lungs
          2. heart
          3. kidney
          4. other guts

          We sometimes talk about the black box vs the white box view of a modules. We have the client's view and the producer's view.

          The rules for using a module form the modules specification. The content of the module (the gory details) are the modules implementation. The specification of the math library for example shows a function called "sqrt" which is called with an double argument and returns a double value:

           		double sqrt( double);
          The documentation further tells us that the argument must not be negative, and if so the returned value when multiplied by itself will be close to the value of the argument.

          Some languages, Java and the UML for example, provide an interface construct that lets us specify a way in which data can be used. C however was much more direct: You list the specification in one file and put the implementation in a different file. The implementation is compiled independently of the programs that use it. The client programs (that use the module) use the #include directive to include the specification. C++ inherits C's approach: a module has two files: the specification full of function headers, and the implementation full of function bodies..

          C++ Modules

          In detail then: to create an independently compiled C++ module you must create two files. One specifies how to use the module. The other describes the implementation. In the specification you typically find:
          1. #includes
          2. a few variables
          3. a few function definitions.
          4. Some classes and other data types.
          5. Some constants
          6. Some function headers or prototypes.

          However in the implementation file you typically find a single #include of the specification and a complete function definition for each function header in the specification. This second more complex file is compiled into a special object file. For example see the header/implementation file [ random.h ] and implementation [ random.cpp ] of a simple random number module. Notice that it does not define a class.

          Typical C++ Specification File

             #ifndef NAME
             #define NAME
             Type function ( arguments );
             class Class_name {
             	Type mutator_name(arguments);
             	Type accessor_name(arguments) const;
             	Type variable;
             }; //class Class_name

          Typical C++ Implementation File

            #include "Name.h"
              Type mutator_name(arguments)
              Type accessor_name(arguments) const

          Rules for Modules in CS202

          To earn full credit for modularizing a program in CS202 each C++ module should appear as two source files and one compiled file. The source code should be a header file (modulename.h) and a compilable file (modulename.cpp). The .cpp file must include the .h file. The implementation .cpp file must be compiled into a .o file. A program the uses the module must #include the specification (modulename.h). It must not include (and so recompile!) the implementation (modulename.cpp).

          The specification needs to have comments to earn readability points!

          The specification (*.h files) are '#include'd in the source code that needs to use them. They are compiled in and recompiled every time the programs that use them are compiled. Normally, we pre-compile the implementations (*.cpp or *.cc) files into object files (*.o) like this:

           		c++ -c .... class.cc

          Example of Module and Client in <a href=UML">

          There are two exceptions to the guideline that implementation is in one file (.cpp) and specification/header are in a different one (.h). See Templates and Inline functions below.

          Skeleton files

          The above rules apply whether you are defining a collection of functions, or are defining a new class. To create a separately compiled class you need a header(specification) like this: [ class.h ] and a separate implementation that looks like this: [ class.cpp ] and defines mutators: [ mutator.cpp ] [ void_mutator.cpp ] and accessors: [ void_accessor.cpp ] [ accessor.cpp ]


          There is a dispensation from the rule of separating headers and code files in C++ in the case of templates. If you declare a template function or a template class then their complete implementation has to be included in a program for most compilers to use it. Thus you may place the implementations of templates inside header files. This will slow down compilation, but may save you rewriting the code.

          Inline functions

          The second dispensation occurs when defining a class that has a very small function that you wish to be executed quickly. These are called #inline functions. They are put inside a class specification. The compiler treats them in a special way. Instead of compiling a call, it copies them into the code where they are called. These functions can be put in header files. However (1) they should no more than one line long, and (2) you should be sure that you are not going to change them.

          For example, the following code is an acceptable header file for a simple counter class that will never need changing:

           	class Counter {
           	private: int i;
           	public: Counter(){i=0;}
           		int value(){return i;}
           		void up(){ i++; }
           		void down(){ i--; }

        . . . . . . . . . ( end of section Modules) <<Contents | End>>

        There are tools that can then make the development work at the terminal simpler. These recall the way the project is constructed and after a change reconstruct the new versions. On UNIX the simplest of these tools is called 'make'.


        The UNIX 'make' program simplifies the task of rebuilding a program when some of the files are changed. It calculates precisely the smallest number of compilations and other operations needed to reconstruct a new version and carries them out in the correct order. 'make' is controlled by a 'Makefile'.

        Write a 'Makefile' using your favorite editor, just be careful to save it with the name 'Makefile'. The file is a text file. It is made of lots of little recipes. Each recipe starts with the name of the file to made, followed by a colon(:) and a list of ingredients. On the following lines come the instructions for making the target from the ingredients. These commands must have a Tab character in front of them. Here is a simple Makefile to help somebody do laboratory number 1:

           flipper : flipper.cpp
           	 g++ -o flipper flipper.cpp
           lab01: lab01.cpp
           	 g++ -o lab01 lab01.cpp

        If you are in a directory with the above Makefile+flipper.cpp+lab01.cpp then

         	make lab01
        compiles lab01.cpp into lab01. And
         	make flipper
        compiles flipper.cpp into flipper. Further
        (with no target) picks the first target in the file: flipper.

        For more about 'make' please see our introductory notes [ make.html ] and detailed documentation [ make.html ] and an advanced model makefile for typical projects: [ makefile.FAQ.txt ] We also have a downloadable UNIX manual page: [ make.man ]

      . . . . . . . . . ( end of section Complex Projects) <<Contents | End>>


        An algorithm is a precise recipe for doing something. They are often implemented as a C++ function. There are thousands of known algorithms. I have some simple example algorithms in [ algorithms.html ] and a set of frequently asked questions [ alg.html ] [ alg.pdf ] with answers. Also check out [ lab07.html ] which is all about timing sorting algorithms.

        Here are some examples from the book and other sources: [ mergeSort.h ] [ mergeSort.cpp ] [ integers2 ] [ selectSort.h ] [ selectSort.cpp ] [ iovect.h ] [ iovect.cpp ] (generic templates [ giovect.cpp ] ) [ selectMain.cpp ] [ integers1 ]

      . . . . . . . . . ( end of section Algorithms) <<Contents | End>>


      Handout: [ pointers.html ] Example code: [ elist1.cpp ] , UML diagrams [ uml1b.html ]

      Example UML model of a family tree linked data structure: [ family.gif ] [ family.mdl ] with possible code: [ Person.h ] [ Family.cpp ] [ Person.cpp ] [ NewFamily.cpp ]

      UML diagram of Employee Link and Employee List [ elist2.cpp ] [ elist.jpg ] You can also (shift/Click) download the Rational Rose model: [ elist.mdl ]

      Linked list with cursor: [ elist3.cpp ]

      Other linked lists developed from elist2: integer [ ilist.cpp ] and generic [ tilist.cpp ] [ tilist2.cpp ]

      Linked Queue: [ LinkedQueue.h ] [ LinkedQueue.cpp ] [ testLinkedQueue.cpp ]

      Data Structures

      [ linked.html ]

      Stack: [ inline_stack.cpp ]

      Linked Queue: [ LinkedQueue.h ] [ LinkedQueue.cpp ] [ testLinkedQueue.cpp ]

      Also see the generic forms (Templates) below.

      The Standard Library and Templates

      Here are some notes on C++ templates. [ Template Functions in functions ] [ templates.html ]

      Generic Linked Lists: [ tilist.cpp ] [ tilist2.cpp ]

      Here is a sample generic input/output vector package. It will read and write files and cin and cout of data of any type into a vector of items of that type [ giovect.cpp ]

      Notes on the STL(Standard Template Library): [ stl.html ] The STL is part of the new American and International Standard C++. Here is a copy (legal) of the draft standard: [ index.html ]

      Inline Functions

      [ Inline Functions in functions ]

      Unified Modelling Language

    1. UML::= Unified Modelling Language. A way to draw diagrams of classes, objects, scenarios, etc. [ uml.html ]

        (UML intro): [ uml0.html ] [ uml1.html ] [ uml1b.html ] [ uml2.html ]
        (UML tools): [ uml3.html ] Plus the following: [ uml1a.html ] [ uml1c.html ] [ uml2.html ] [ uml4.html ] [ uml.glossary.html ] [ uml.html ]

      More complete descriptions of UML can be found in [ uml.html ] my samples of mathematical specifications.

      Rational Rose

      Our Windows machines in JB361 can access the latest version of Rational Rose.

      Down loadable (shift/click!) models that can be used with Rose: [ lab01.mdl ] [ Stack.mdl ] [ elist.mdl ] [ family.mdl ] [ family.mdl ] [ mem.mdl ] [ CSciNetwork.mdl ]

      Examples from text book: [ elist.mdl ] [ clock1.gif ] [ clock2.gif ]

      A package defining parts of C++ that can be imported and used in other models: [ c++.ptl ]

      Deriving new class from old ones


      1. inheritance::= See http://cse.csusb.edu/dick/cs202/inheritance.html


      2. abstraction::= See http://cse.csusb.edu/dick/cs202/abstraction.html


      3. polymorphism::= See http://cse.csusb.edu/dick/cs202/polymorphism.html

        Examples: [ poly1.cpp ] [ poly2.cpp ] [ poly3.cpp ] [ poly4.cpp ] [ poly5.cpp ] and [ polystud.cpp ] [ polystud2.cpp ] [ polystud3.cpp ]

      . . . . . . . . . ( end of section Deriving new class from old ones) <<Contents | End>>


      [ q1a.htm ] [ q1.cpp ]


      Frequently Asked Questions and Answers for C++(Lite) [ http://www.cerfnet.com/~mpcline/C++-FAQs-Lite/ ]

      General C++ sources: [ c++.html ]

      (C++ Tutorial): [ http://www.cs.uwa.edu.au/programming/c++.tutorial/ ] [ typedef.html ]

      (C++ Examples): [ http://cse.csusb.edu/dick/examples/ ]

      (USENET): Discussions from USENET News: [ pointers.html ] comp.lang.c++.moderated

      (Standard): [ http://cse.csusb.edu/dick/c++std/ ] [ index.html ]

      UNIX Books

      Here is a $10 book on UNIX from a usually reliable publisher: Daniel J Barrett, Linux pocket Guide, O'Reilly Feb 2004 $9.95 ISBN 0-596-00628-4. Look in your local Barnes and Noble or Borders bookstore.

      I have a sampling of other books in my office that you can look at.

      UNIX Links

      [ commands.html ] [ unix.FAQ.txt ] [ CS_FAQ.html ]

      The command

      will run a menu-driven shell that helps you do most of the things you might want to do.


      [ vi.txt ] [ vi.FAQ.txt ] [ vi.commands.txt ] [ vi.archives.txt ]

      Software Design

      [ wiki?SevenPrinciplesOfSoftwareDevelopment ]

    . . . . . . . . . ( end of section Resources) <<Contents | End>>


  1. accessor::=`A Function that accesses information in an object with out changing the object in any visible way". In C++ this is called a "const function". In the UML it is called a query.
  2. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  3. class::="A description of a set of similar objects that have similar data plus the functions needed to manipulate the data".
  4. constructor::="A Function in a class that creates new objects in the class".
  5. Data_Structure::=A small data base.
  6. destructor::=`A Function that is called when an object is destroyed".
  7. Function::programming=A selfcontained and named piece of program that knows how to do something.
  8. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  9. mutator::="A Function that changes an object".
  10. object::="A little bit of knowledge -- some data and some know how". An object is instance of a class.
  11. objects::=plural of object.
  12. OOP::="Object-Oriented Programming", Current paradigm for programming.
  13. Semantics::=Rules determining the meaning of correct statements in a language.
  14. SP::="Structured Programming", a previous paradigm for programming.
  15. STL::="The standard C++ library of classes and functions" -- also called the "Standard Template Library" because many of the classes and functions will work with any kind of data.
  16. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  17. Q::software="A program I wrote to make software easier to develop",
  18. TBA::="To Be Announced", something I should do.
  19. TBD::="To Be Done", something you have to do.
  20. UML::="Unified Modeling Language".
  21. void::C++Keyword="Indicates a function that has no return".