Home Page

Arrays
Classes
Abstract Data Types
Dynamic Memory Allocation
Operator Overloading
Lists
C++ Style Strings
Linked Lists
Stacks and Queues
Variable Data Types
Templates
Sorting
Basics

Unix Account:     mp.cs.???.???
Use Teraterm Pro to connect and work within Unix
Use WS_Ftp to transfer files to Unix system from home



Basic Unix Commands:
cd                go to home directory
cd name     change directory to name subdirectory
cd ..            step back one level in directory
chmod        sets security (in your home dir type chmod 700 .<.cr> to set security)
mkdir          make a directory
rmdir           remove directory
rm               remove filename
mv               move file or directory
cp               copy file or directory
ls                list current directory files
ls -l             adds details to file names listed
ls -R           shows tree branch of directory
touch          to "touch" a file will update the time stamp


Editor:       (pico)
basic text editor.  Can work at home with DOS editor, NotePad, or Turbo C++.  Note that you should be careful to use tab setting of 8 spaces to match with pico.  Be careful to use tabs and not spacebar when writing code to keep all things lines up properly.  Tabs MUST be used when creating a Makefile.



Compiler:     (g++)
Options:
-c     creates object file
-o     allows for specific naming of file (must be directly followed by name)
-g     for debugging (puts debugging info into exe but makes it larger)
-O     optimizer
-I include          include_dir
-Wall          gives all warnings
-W num          turns off or on warnings (can specify)
-l name          links library (ie  -lm links math library)
-L library_dir

Makefile:

     For each assignment you need a makefile.  To generate, go to the directory with your source code and type… pico Makefile <cr>.  This brings up the pico editor then you type the following:

format ŕ           target : dependancies
                        command

example:       CC = g++
CCFLAGS = -Wall -O

test1 : test1.o
     $(CC) $(CCFLAGS) -o  test1  test1.o  -lm

test1.o : test1.C
     $(CC)  -c  $(CCFLAGS)  test1.C

clean:
     -rm  *.o  test1

When you want to compile and make an executable you type .. make <cr>.

When you alter your source code and wish to make another executable make sure that you first type..  make clean<cr> to remove all object files and your executable.


There are several changes between C and C++.  In C you would code the following:

#include <stdio.h>

void main()
     {
     printf("Hello World\n");
     }

The differences in C++ are as follows:


#include

All standard libraries are available to use in C++ and will work.  <cslib.h> is not available because it was written as a "crutch" in the 240 class.  The way the libraries is called is slightly different :

<stdio.h>     becomes     <cstdio>
<stdlib.h>     becomes     <cstdlib>
<math.h>     becomes     <cmath>
<string.h>     becomes     <cstring>
<ctype.h>     becomes     <cctype>

Note as a standard, you add a `c' to the beginning and drop the `.h' at the end.


void main( )

     In C++ we will write as  int main( ) and at the close of the program we will include   return(0); before the last }.




Comments:

     When writing comments in C++ you should no longer use the   //  method for commenting.  From this point forward you should use   /*  comment here  */ .  This is more acceptable across the board and less likely to cause problems for you if you get in the habit now.

clrscr( );

     This method for clearing screen doesn't work in C++.  You have to use the form feed character.  Remember ..   \n, \t, \b (backspace),   \a (bell),  now use   \f (formfeed).  This will put a page to the display and will run the current screen "over the top".

printf:

     The problem with  printf  is that you have to specify the exact format of the information you are going to print.  The  printf  statement still works but there are problems with the   stdio   library so there is a better way called streaming.  You will want to   #include <iostream> in your program.




#include <iostream>

iostream  contains 3 streams automatically available to you for use in your programs:

cin      - for input
cout     - for output
cerr     - for output (usually error codes)

cout:

Here's how it works.  Say that you have coded:

….
int d = 7;
float f = 3.14;

to output using iostream you would eliminate the printf and replace it with:

cout << d;
cout << "\n"
cout << f;

<< is an output operator and basically you are "overloading" the function cout which can be done in C++ (remember part 12 of CSCI240).

You can also "chain" the cout statement to place all variables on the same line of code:
          cout << d << "\n" << f;

This works because the computer will evaluate it similarly to the way it would evaluate the declaration of      int a=b=c=d=3;     as     a=(b=(c=(d=3)));  So the program sees the chained statement     
cout << d << "\n" << f;       as       ((cout << d) <<"\n" <<) <<f;

endl:

     Using the "\n" is not the preferred way to add a new line return in C++.  The manipulator endl is much better.  Now we can write…

          cout << d << endl << f;

cerr:

     The stream   cerr  works much the same as   cout   with one important exception.  When you use  cout  the information is sent to a buffer and when the buffer is full it is sent to the display.  This is fine except if you are using   cout   statements to work on debugging your code.  If you use   cerr  each line will print out directly.  This is a slower output but will help you considerably when debugging.
     The   endl statement also flushes the buffer so put it at the end of each line.

Note:     When using  cout  to print a character array named  s  you can write   cout << s   because it will point to the start of the character array and does the rest automatically.

cin:

The stream   cin   works much the same as   cout .   It is to replace the  scanf  statement in C. The  scanf ("%d", &variable); statement is cumbersome because you have to pass the variable by reference to the function  scanf .   When you input, you can code as follows:

cin >> d >> f >>s;

     Note that a string will input until it hits a "white space character" (space) so at this point we only know how to input one word at a time.

data re-direction:
Data re-direction works the same way as in C.  at the prompt (mp%) type:

prog1<p1.dat>p1.out

flush:

     the command  flush will empty the data buffer for the output.  When you are printing statements and retrieving input from the user you have to flush at the end of the  cout  before the  cin is written.

Sample Code:

#include <iostream>

int main()
{
int d;
float f;
char s[80] = "Wow!";

cout << "Hello World" << endl;

cout << "Input a float. " << flush;
cin >> f;

cout << "Input an integer. " << flush;
cin >> d;

cout << "Input a string. " << flush;
cin >> s;

cout << "The value for d is " << d << endl;
cout << "The value for f is " << f << endl;
cout << "The value for s is " << s << endl;

return (0);
}

bool:

You can use the variable type  bool  when you want something to have a logical operator of either true or false.  The conditions  true  and   false  are designated to have the value of   true=1  and  false=0.

Input/output formatting:

get is an overloaded function and can determine what the usage of the function will be depending on the arguments passed in.  Therefore you can use the following variations…

cin.get(char &ch);  This is the structure used to get a character from the keyboard  if you were to use it in code, it would be written as   cin.get(ch);  This could also be coded as cin >> ch;

cin.get(char *buf, int n);   This array of characters has  `n'  elements in it and is guaranteed to put and end of line character at the end of the array or will go until it hits a new line character and then put a `\0' character and return to the program.

cin.get(char *buf, int n, char term);  This is more rare.  It does the same as the one listed above but allows you to designate what the terminating character is.

Note:  This form may create a problem because it leaves the "\n" character there.  This may sometimes be a problem but may also come in useful at times.  Just be aware of the fact.

Example of problem:
               …
while (cin)
     {
     cin.get(buffer,256);
     cout << buffer;
     }

This will cause an infinite loop because it is thrown off by the "\n"

More input functions:

cin.getline(char *buf, int n);  Once it reaches a new line char, it will throw it away and not put it in the buffer.  Both the  get  and the  getline  functions can have embedded or leading whitespace before or during the string.

cin >> buffer   will throw away leading whitespace and stop when it encounters  and additional whitespace.

format output:

Manipulators are used to replace many C functions.  
endl      -replaces the "\n"
flush     -flushes the print buffer but does not print new line.

There are many more…

setting width:
cout.width(int n);  will set the width for the next output only.  The integer n indicates the minimum number of characters used in the output and numbers are right justified by default.

*width is the only option that applies to only the next object to be printed to output.  All other options remain until reset to another option.

setw(n);  is an easier way to set the width of a field.  You must  use   #include<iomanip>.
**width can also be used in input streams.  Example:    cin.width(4);
decimal output:

to force integers to print in decimal format…

cout.setf(fmt flags);
cout.setf(fmt flags, fmt flags);

Use the first when only one option is available.  Use the second when two or more options are available.

cout.setf(ios::dec,ios::basefield);  -note no spaces.  this prints in decimal format
cout.setf(ios::oct,ios::basefield);   this formats in octal format
cout.setf(ios::hex,ios::basefield);  this formats in hexadecimal format
**(ios:: is a scope identifier and tells the second thing where to look)


distinguish the outputs as follows:

  1234          - decimal
 01234          - octal
0x1234          - hexadecimal

If you would like to print the output in a given format, you may use the flag names showbase:

cout.setf(ios::showbase); - this will option on and print in the above format.
cout.unsetf(ios::showbase); - this will turn the option off.

Other flags in output stream classes:

by default, all numbers and strings are right justified.

cout.setf(ios::left,ios::adjustfield); - will format all output to left justified.
cout.setf(ios::right,ios::adjustfield); - will format all output to right justified.
cout.setf(ios::internal,ios::adjustfield); - will be used if you want to do something like
adding a `-` to the left  side of a column of numbers indicating a negative number and still justifying the numbers to the right.

There is more on this subject in Chapter 2 Section 13 of the Kalin textbook

cout.fill(char ch);  -  You can use this if you want to fill all blank spaces in a field with a `*' or any other character:
****123
**26747
***1234

cout.setf(ios::showpos); - this will attach a `+' sign to all positive numbers.
cout.unsetf(ios::showpos);  -  this will turn off the option.

combinatorial |:

There is a difference between || which is an `or' operator and  | which combines.
cout.setf(ios::showbase|ios::showpos);  -  this will combine the two flags as one operation.

flags for floating point numbers:

cout.setf(ios::fixed,ios::floatfield);  - fixed state.
cout.setf(ios::scientific,ios::floatfield);  - scientific notation
cout.setf(0,ios::floatfield);  -general notation

More output flags:

cout.setf(ios::showpoint);     This will print out decimals so when it prints it will force it to print all trailing zero's.

cout.setf(ios::uppercase);     when using scientific notation, 3.14+e25 becomes 3.14+E25 or when you are displaying in hex format, 0x325 becomes 0X325.

Setting precision:     default precision is set to 6 places

cout.precision(int n);     This sets precision until you set it again.
     general-  this is actual digits not including the + or - but including the decimal.
     float -       how many to print after the decimal point.

setprecision(4);     is another way to set the precision but if you use this you must use the #include <iomanip> manipulator.

ios::showpos   only applies to decimal numbers. It will show a + sign on all positive numbers.

One more manipulator:
cout << setiosflags(ios::showpos);          (to turn on)
cout << resetiosflags(ios::showpos);     (to turn off)



Here is an example of formatting manipulators to try:

#include <iostream>
#include <iomanip>

int main()
     {
     int d = 1234;
     double pi = 3.1415926;
     char msg[] = "This is really fun";

     cout.setf(ios::showbase|ios::showpos); //remember | is a combiner
     cout << d << oct << " " << d << hex << " " << endl;

     cout << pi << endl;
     cout << setprecision(20) << pi << endl;

     cout << setw(20) << msg << setw(6) << d << endl;

     cout.setf(ios::left,ios::adjustfield);
     cout.unsetf(ios::showpos);
     cout << setw(20) << msg << setw(6) << d << endl;
     cout << 3.5 << endl;
     cout << setiosflags(ios::showpoint) << 3.5 << endl;
     return (0);
     }



There is a difference between integers in Turbo C and C on mp.  In Turbo C an integer ranges from -62767 to +62767 (check this amount).  In mp an integer ranges from -2 billion to +2 billion which is the same as a long int in Turbo C.




Control Structures:
Any program can be written with three main elements: statements, decisions, and loops.

If you need to break out of a program you can use the  break;  command.  There are a few things to know though:

break:  will get you out of a block of code one level of a for loop or switch statement.  If you use break;  in an  if  statement, it will kick you out of the current loop you are in.  Break will  kick you out of whatever LOOP you are in NOT just the decision which contains the break statement.

Example:

#include <iostream>

int main()
{
int i, j;
for (j=0;j<1;j++)
          {
          for (i=0;i<1;i++)
               {
               break;
               cout << "A";
               }
          cout << "B";
          }
     cout << "C";

     return (0);
     }

The printout would be:     BBC

Variable declarations:

In C++ you can put declarations of variables where you need them.  Note that if you declare a variable mid-program, it only exists and available while the program is in the block of code where it is declared.  Once you are out of that  {  }  it vanishes and is forgotten.

Example:     for (int j=0; j<10; j++)

Continue:

continue is similar to the break command except that it will "bag" the rest of the body of a loop and go straight to the test (or condition).  It can only be used in loops.  Like break, it ignores if statements on exit and jumps out to the nearest for, while, or do..while loop.

Example:
while (1st condition…)
     {
     …
     …
     …
     if (2nd condition …)
          continue; /* This will jump straight back to */
                          /* the while conditional statement */
     …
     …
     …
     }

Application example of continue:

#include <iostream>

int main( )
     {
int score[80];
int sum=0, num=0;
     for (int j=0; j<80; j++)
          {
          if (score[j] <50)
               {
continue;
}
          sum += score[j];
          num++;
          }
     double average = double(sum)/num;
     cout << "The average for " << num << " people is "
            << average << endl;
     return (0);
     }


goto:

If you need to break out of more than one level you can use the goto command.  Unlike the break and continue statement, the goto is an unconditional statement.  It is only to be used in certain instances and should be avoided unless completely necessary.

to use, you would type   goto label;     Label is any name you give indicating a section of code.  At that section of code you would then type   label:   The program would then continue at that point.

recap:

continue;     - stay in loop but skip to increment and test
break;          - break out of immediate loop (not if statement)
goto;               - unconditional jump to a specified label name.

switch:

switch statement is similar to cascading if, else if, else loop.  It's great for char by char input.

switch(variable_name)
{
     case 1:
          ~~executable code ~~;
          break;
     case 2:
          ~~executable code ~~;
          break;
     default:
          ~~executable code ~~;
}

You can also have several cases back to back with one set of executable code for several choices.  Note that all cases except default have to be scalar constants (single pieces of information) of int or char type.  The order of cases is not important and default can be anywhere but there MUST be a break statement in each case to keep it from filtering down to the next condition.