Kurt Bingham 2/2008

Home

C  

C code quick ref with sample code.

Most code can be cut and pasted into a .c file, compiled, and run. It is for my own quick reference. In most cases, if I need to build a powerful application, I will use VB or C#, so I may need to get my bearings getting started with something in C/C++, and this is useful.

 

It's actually a bit difficult to get nice looking code into HTML format. I used C++ Code Export to format this. It's an excellent shareware program. 

In order to prepare for C exams, I read the K&R book  cover to cover, obtained the O'Reilly 'C in a Nutshell' (which covers modern versions of C like C99  as well, and goes into much more detail than the K&R book), and viewed VTC's course on C. After so doing and studying for a few weeks, I obtained a score in the top 1%.

 

C++

 C++ The Complete Reference/ Horton's ANSI C++

 

 

C reference

bitwise operators | conditional (?) | if-else | switch  | print&escape char | loops | break&cont | extern&static

pre-processor (#) | pointers | ++--| arrays | command line | function ptrs | struct | typedef | < > (i/o) | files

includes

       

 

 

Integer bitwise operators

& => if both = 1 then result = 1 else 0

0001 1010 &

1101 0010 

0001 0010

|  = > if either is 1or both are 1 then result is 1 else 0

0001 1010 |

1101 0010

1101 1010

^ Xor = > if either is 1 then result is one else 0

0001 1010 ^

1101 0010

1100 1000

<< Left shift => push bits left

1101 0010  << 2 = 0100 1000

>> Right shift => push bits right

 

~ Complement

~1101 0001 = 0010 1110

 

 
   

conditional (?)

(condition) ? true: false


#include <stdio.h>
int main (int argc, char *argv[])
{
  int a = 1;
  int b = 4;
  printf("%i>%i : %s\n",a,b,(a > b ? "true":"false"));
  printf("%i<%i : %s\n",b,a,(a < b ? "true":"false"));
}

 

Print and escape chars

 

 

printf(".... %d", dvar);

printf("....%c", cvar);

etc

%d (or %i)

int

%c

char

%f

float

%lf

double

%s

string
%x hexadecimal

source

Scanf, getchar(); etc

\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\ooo ASCII character in octal notation
\xhh ASCII character in hexadecimal notation
\xhhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal.

For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese character for one is \x4e00".

 

switch

switch (var)
{
case value: <code>;
break;
case valueb1:
case valueb2:
<code>;
break;
default:
<code>;
}

 

#include <stdio.h>
int main (int argc, char *argv[])
{
        char        buffer[5];
        if(argc < 2)
        {
                printf("Not enough options\n");
                exit(1);
        }
        strncpy(buffer, argv[1], 4);
        switch(buffer[1])
        {
                 
        {
        case '?':
                printf("Help\n");
                break;

        case 'A':
        case 'a':
                printf("Option A\n");
                break;

        case 'B':
        case 'b':
                printf("Option B\n");
                break;

        default:
                printf("don't know what you selected\n");
        }
        }
}

 

 

if else

if (condition)
 <code>;
else if (condition)
<code>;

else
<code>;

 

#include <stdio.h>
int main (int argc, char *argv[])
{
char buffer[10];
if (argc < 2)
{
   printf("Not enough options\n");
   exit(1);
}
strncpy(buffer,argv[1],9);
if (strcmp(buffer,"/?")==0)
   printf("Help\n");
else if (strcmp(buffer,"/A")==0)
   printf("Option A\n");
else
   printf("Don't understand option\n");
}

 

 

do

do {...} while ( x !='V');


while

while (condition) {....}
 

for

for (var=val;condition;increment) {...};

#include <stdio.h>
int main(int argc, char *argv[])
{
char i = 0;
printf("Type in a 9 to quit");
while (i != '9')
{
   i=getchar();
   getchar();
   printf ("You typed %c. \n",i);
 if (i=='9') {break;}
}
  printf("loop over \n");
}

 

 

#include <stdio.h>
main()
{
int k = 0;
for ( k = 0; k<10;k++)
 {
  printf("k %d\n",k);
 }
}

 

break;

continue;

 

break exists the inner most set of instructions; continue leaps out and continues with the next one


#include <stdio.h>
main()
{
int k = 0;
do
  {

   k = getchar();
   getchar();
   if (k=='s')
    {
     printf("skipping \n");
     continue;
     }
  printf("ascii %d \n",k);
 } while (k !='q' && k !='Q');
}

 

 

 

Externs; statics

 

float x;

main (){...}

-----

extern float x;

func xuser() {...}

---

static int x;  (only available in the c file it appears in)

---

register int x; (requesting an actual register=high use variable)

---

 

extern int var1; (declared in another .c file)

--

extern int  var2, var3;

ver 1.) static int var1 = 2;  (error because static only available in file)

ver 2.) int var1 = 2; (ok)

 

 

 

.c files are for functions

.h are for declarations

#include "dir/dir1/dir2/myinclude.h"

 

#include; #define #if

 

 

 

pre processor

#define X 2.17

#define MIN(A,B) ((A<B) ? A:B)

#if Caller == "DEV"

#define MODE = "debug.h"

#elif Caller == "PRD"

#define MODE = "prod.h"

#else

#define MODE = "qat.h"

#endif

#include MODE

#ifndef MODE

#define MODE

#endif

 

 

 

Pointers

 

& operator returns addy of var

* is used when declaring a pointer and also to dereference a pointer

 

int j = 1; (a simple int)

int *intPtr;  (pointer to int, use * when declaring a pointer; when put in front of a pointer, it references the value held in the addy pointed to by the pointer)

intPtr = &j; (intPtr is a pointer...you can assign it the addy of j)

int b = *intPtr; (now b, an int, gets the value pointed to by intPtr)

 

 

char a[12], *p = &a[0];

Then the following statements are true

*p ==a[0] ;

*(p+1) == a[1];

*(p+2) == a[2];

etc

 

*p++ moves to the next higher addy of the pointer data type in memory


#include <stdio.h>
main()
{
int a = 1;
int b = 5;
int ar[5];
int *intPtr; /* intPtr is a pointer to vartype of int */
printf("intPtr is a pointer to type int\n");
printf("intPtr: %x\n",intPtr);
intPtr = &a; /* give intPtr the address of a */
printf("intPtr after =&a: %x\n", intPtr);
b = *intPtr; /* y is an int--give it the dereferenced value of intPtr */
printf("The value referenced by intPtr: %d\n",b);
*intPtr = 0/* clear the address of *intPtr */
intPtr = &ar[0]; /* now point intPtr to the first element's addy of ar */
}

   

increment and decrement

Moving through an array via pointers, using ++ (--)

#include <stdio.h>
main()
{
char c[] = "This is my char array";
  char *cp = c;
  int i=0;
while (*cp) /* while *cp is non-zero */
{
printf("Addy: %x, %c\n",cp,*cp); /* cp is the addy; *cp is the char stored there */
cp++; /* increment the pointer by char size in memory */
}
for (cp = c, i=0; i < 20; i++)
{
*(cp+i) = '\0'/* nulling out the entire string --or if i >=20, big problems */
}
}

 

 

 

Arrays

 

char c[] = "Greets";  (actualy last char = '\0' NULL

char c2[][10] = {"Hey","Whats up", "Yo"}; (where 10 is the length of the longest string intended)

 

 

 

 

 

 

Array of pointers

 

 

/* returns a string naming the day based in input of int n */

/* static don't change values between calls */

char *weekday(int n)

{

static char *name[] = {"Unknown","Mon","Tues","Wed","Thurs","Fri","Sat","Sun"};

return (n<1 || n>7) ? name[0]:name[n];

}

 

 

 

char *weekday(int n)

{

static char name[][7] = {"Unknown","Mon","Tues","Wed","Thurs","Fri","Sat","Sun"};

return (n<1 || n>7) ? name[0]:name[n];

 

}

 

 

 

Command Line Argument

main (int argc, char *argv[]) {...};

 

Echoes the command line argument

#include <stdio.h>
main(int argc, char *argv[])
{
        /*~~~~~~*/
        int k = 0;
        /*~~~~~~*/

         for(k = 1; k < argc; k++)  
        {
                printf("%s%s", argv[k], " ");
        }

        printf("\n");
        getchar();
}

 

 

 

 

 

function pointer

 

 

#include <stdio.h>
void my_func1(float a, float b){printf("%f\n",a+b);}

int main()
{
void (*func1)(float,float);
func1=&my_func1;
func1(2.2,3);
getchar();


return 0;
}

 

 

 

 

 

structs

 

 

 

struct <name>

{

<var>;

<var>;

..

}

 

 
//Program using a struct in C

struct Star
{
float diameter;
float mass;
float x,y,z;
char *s_type[];
};
main(){
struct Star mystar = {100.0,254,0,0,0,"sun"};
mystar.mass = 2.34;
printf("star type %s \n", *mystar.s_type);
printf("diameter %f \n",mystar.diameter);
printf("mass %f \n",mystar.mass);
getchar();
}

 

 
#include <stdio.h>
struct Star
{
float diameter;
float mass;
float x,y,z;
char *s_type[];
};
void DoStuff(struct Star *mystar ){
mystar->diameter = 110;
printf("%f\n",mystar->diameter);
mystar->diameter = 115;
printf("%f\n",mystar->diameter);
getchar();
};
main(){
struct Star myS = {1,100,0,1,0,"Jupiter"};
printf("%f\n",myS.diameter );
DoStuff(&myS);
}

 

 

 

Type Def

typedef char *STRING;

STRING a,b,c;

 

stdin;

stdout;

stderr;

putchar();

getchar();

 

putchar(tolower(mychar));

 


#include <stdio.h>
main(){
char c;
while ( (c=getchar()) != EOF)
{
putchar(tolower(c));
}
}

 

 

 

 

< modifies the standard in

> modifies the standard out

In order to change the standard input what we do is this

lower < upper.txt

lower < upper.txt > outfile.txt

 

 

 

 

 

 

 

 

copies a source file from the command line to the standard output

calls: filecopy src.txt   =types contents of src.txt to screen

filecopy src.txt > outfile.txt = copies the contents of src.txt into outfile.txt


#include  < stdio.h > 

main()
{
        /*~~~~~~~~~*/
        FILE         *fp;
        FILE         *fp2;
        /*~~~~~~~~~*/

        fp  =  fopen("c:\\mynewfile.txt""r");
        fp2  =  fopen("c:\\mynewOut.txt""w");
        fclose(fp);
        fclose(fp2);
}

#include <stdio.h>

main(int argc,  char  *argv[])
{
        /*~~~~~~~~*/
        FILE         *fp;
        /*~~~~~~~~*/

        void filecopy(FILE  *,  FILE  *);
        while (--argc > 0)
        {
                ++argv;
                fp  =  fopen(*argv, "r");
                printf("target %s\n",   * argv);
                filecopy(fp, stdout);
        };
}

void filecopy( FILE  *fpsrc,  FILE  *fptgt)
{
        int k;
        while ((k = getc(fpsrc))   !=  EOF)
        {
                putc(k, fptgt);
        }
}

CGI

This is basically C with the stdin and stdout directed to respond to to browser requests and execute code on the server in a cg-bin directory with execute permissions. As Tim Heagarty warns us via VTC (C programming 2007 CGI section), this is how you can end up with people blowing open your server and causing trouble.

I don't see any reason myself anyway, for getting too far into something so barebones for web programming as C. I am interested in C because you can do a lot of low level operations with it--thus if you want to program for a microprocessor with a very thin OS and basic compiler, you need C; plus anything will run ANSI C. However, for a server, you have complete control, so there is no need to punish yourself. I'd just rather load IIS and do everything in ASP. There is plenty of heartache and hassles in managing databases, ajax, cotnrols, classes, events, cache, SQL etc. You don't need to add low level CGI to the mix. Most of that has been thoroughly covered. The new heroes will do advanced things with the advanced controls and IDEs currently available.

Every programmer needs to know C, of course, and knowing C is enough to get you started with CGI thereby allowing you to start programming for a mini-server with virtually nothing, but after you do some CGI,\ you might want to check out ASP.net.

Anyway, this tutorial looked like one of the better ones.

 

 

 

Includes, for reference. I made sure these all link to places with actual useful information no how to use all of the useful functions.

stdio.h

ctype.h

string.h

 

 

 

 



C++ topics

 

C++ compilers can compile C. C++ is simply C with classes, or C+1 (C++)

 

 

namespace

 

 

 

 

 

 

 

 

 

/* namespace */
#include <iostream> namespace constants
{
        static float pi  =  3.14159;
                 /* a constant put in a constants namespace */
};
int main()
{
        std::cout  <<   "namespace constants "  <<  constants::pi  <<   "\n";
        return 0;
}

 

classes (very basic class constructor: don't do it this way)

 

/* basic circle class */
#include <iostream> 

using namespace std;
static float pi =  3.14159;
class CCircle
{
private:

        /*
         * private member vars aren't available outside the class ;
         * you have to change their values with public properties or methods
         */
        float r;
public:

        /*  public 2nd half of our two part 'constructor' */
        void create (float);

        /*  cast our area as a float, * returns double */
        float area()
        {
                return  (float)
                pi * r * r;
        }
};

/*
 =======================================================================================================================
    this will handle arguments for our constructor ;
    I usually put method def with method declaration inside the class ;
    but this shows how you can have the method def outside of a class, ;
    resolving with ::
 =======================================================================================================================
 */
void CCircle::create(float ir)
{
        r  =  ir;
};
int main()
{
        cout  <<   " creating the circle \n";
        CCircle mycircle;
        cout  <<   " area after default constructor "  <<  mycircle.area()   <<   "\n";
        mycircle.create(13.1);
        cout  <<   " area of a circle after create "  <<  mycircle.area()   <<   "\n";
        return 0;
};

class with a normal constructor and overload

 

/*
 * class with constructor overload ;
 *  demonstrates using a class constructor and overloads ;
 *  of that constructor
 */
#include <iostream> 

using namespace System;
using namespace std;
static float pi =  3.14159;
class Circle         /* class def */
{
private:
        float r;
public:

        /*  create a func to return the private r */
        float radius()
         
        {
                return r;
        };

        /*  incoming r constructor overload */
        Circle(float ir)
        {
                r  =  ir;
        }

        /*  default constructor r = 1 overload */
        Circle()
         
        {
                r  =  1;
        }

        /*
         *  cast our area as a float for no reason at all except it looks cool to ;
         *  put (float) in front of a var or expression
         */
        float area()
        {
                return  (float)
                pi * r * r;
        }
};
int main()
{
        cout  <<   " creating default circle \n";

        /*  the new default constructor makes the radius 1 */
        Circle mycircle;
        cout  <<   " default r/area "  <<  mycircle.radius()   <<   ","  <<  mycircle.area()   <<   "\n";
        cout  <<   " creating another circle \n";
        Circle mycircle2(3);
        cout  <<   " new r/area "  <<  mycircle2.radius()   <<   ","  <<  mycircle.area()   <<   "\n";
        return 0;
                                 /* you can resolve namespace members with :: */
};

enumerated type

/*
 * Enumerated type. Enums by default assign integer values to the list members. ;
 * running the program demonstrates the values of myobj and the enums of polys
 */
#include <iostream> 

enum polys 
{
        square, rectangle, circle
};
polys myobj;

int main()
{
        myobj  =  circle;
        std::cout  <<   "myobj "  <<  myobj  <<   "\n";
        std:: cout <<   "myobj == circle "  <<  ((myobj == circle)   ?   "true" : "false")   <<   "\n";
        std::cout <<   "myobj == 2 "  <<  ((myobj == 2)   ?   "true" : "false")   <<   "\n";
        std::cout <<  polys::circle;
}

 

try/catch/finally block

/*
 * try-catch block example ;
 * in which an error is introduced. Set the value of mybuff ;
 * to something other than 21 to see program without errors
 */
#include <iostream> 

using namespace std;
void main()
{
        try
        {
                char         *mybuff;
                mybuff  =  new char[256];
                mybuff = "21";
                if (atoi(mybuff)   ==  21)  throw  "Invalid value for mybuff";
                printf("No errors...");
        }

                 /* end try */
        catch(char  * e)
        {
                printf("Error %s\n", e);
        }

                 /*  end catch */
        finally
        {
                printf("This is always executed \n");
        }        /*  end finally */
}     

destructors

 

 

 

 

 

 

 

 

 

 

 

 

 

/*
 *  destructor ~classname ;
 *  if the class calls another class and this class is closed ;
 *  you can end up with a memory leak. In the destructor, you'd ;
 *  want to clean up subclass' stuff with delete etc.
 */
#include <iostream>

using namespace std;
class star
{
        class weird
        {
        public: double myval;
        };
private:
        char         *stype;
        double mass;
        double radius;
        weird         *myweird;
public:
        star(char  * istype,  double imass,  double iradius)
        {
                stype  =  istype;
                mass  =  imass;
                radius  =  iradius;
                myweird  =  new weird;
        };
        void tostring()
        {
                printf ("%s,%s,%s\n", stype, mass.ToString(), radius.ToString ());
        }
        ~star()
        {
                delete myweird;

                /* put necessary clean up code in here */
        }
};
void main()
{
        cout  <<   "creating a star object \n";
        star mystar("Sun"11);
        cout  <<   "using the tostring() func to display contents of class " ;
        mystar.tostring();
        cout  <<   "\n the instance will be destroyed (along with *myweird, \nusing the destructor) now in 5,4,3...\n";
}

static_cast and dynamic_cast

 

/* static and dynamic casts */
#include <iostream>

class form
{
private:
        int h,  w;
public:
        form(int ih, int iw)
        {
                h = ih;
                w = iw;
        };
};
class formbtn  :
         public form
{
private:
        bool button;
public:
        formbtn(int ih,  int iw,  bool inbtn)
        :
        form(ih, iw)
        {
                button = inbtn;
        };
};
void main()
{
        form form1(11);
        formbtn form2(22, false);

        formbtn * fv  =  dynamic_cast < formbtn * > (&form2);
        form        * fv2  =  static_cast < formbtn * > (&form2);

        /*
         * formbtn* fv3 = dynamic_cast<formbtn*>(&form1);
         *  //compile fails bc form1 is not a derived class
         */
        form        * fv3  =  dynamic_cast < formbtn * > (&form2);
                 /* compile succeeds bc form2 is derived from form 1 */
        double dbl  =  static_cast<double> (25);
        std::cout  <<  dbl  <<   "\n";
        int i  =  static_cast<int> (2.3565);
        std::cout  <<  i  <<   "\n";
}

templates (generics in VB?) In any case, their function in C++ is easy to understand and doesn't require much work to put into use. They can also be applied to classes.

/*
 * simple template that accepts different ;
 *  types and returns a bool or the greatest of the two
 */
#include  "stdafx.h"

#include <iostream>

using namespace std;
template <class B> bool isGreater(B a,  B b)
{
        return ( a  >=  b ?  true : false);
};
template <class G> G Order(G a,  G b)
{
        return (a >= b ? a : b);
};
void main()
{
        cout  <<  isGreater(21)   <<   "\n";
        cout  <<  isGreater(1.3431.6)   <<   "\n";
        cout  <<  isGreater('a''k')   <<   "\n";
        cout  <<  Order('a''k')   <<   "\n";
        cout  <<  Order(1, -1)   <<   "\n";
        getchar();
}

 

/*
 *  operator overloading ;
 *  redefining the float and int operators
 */
#include <iostream>

using namespace std;
class cfloat
{
private:
        float fx;
public:
        cfloat(float ifx)
        {
                fx  =  ifx;
        };

        /* if you just have one, it'll default to that */
        operator float()
         
        {
                 return fx + 1;
        }

        /* defining operators differently */
        operator int()
         
        {
                return fx - 1;
        }
};
int main()
{
        cfloat x(0);
        cout  <<   " x now "  <<   (float) x  <<   "\n";
        cout  <<   " x after "  <<   (int) x  <<   "\n";
}


&Variable reference

/* reference to a variable */
#include <iostream>

using namespace std;
void main()
{
        int i  =  0;

        /*~~~~~~~~~~~*/
        int & ir  =  i;
        /*~~~~~~~~~~~*/

        cout  <<   " i before "  <<  i  <<   "\n";
        ir++;
        cout <<   " i after "  <<  i  <<   "\n";
}

Operator Overloading

 

Operator Overloading

/*  overloading +,- operators to handle vectors */
#include <iostream>

using namespace std;
class vector
{
private:
        double x,  y;
public:
        vector(double ix,  double iy)
        {
                x  =  ix;
                 y  =  iy;
        };
        void print()
        {
                printf("%d,%d\n", x, y);
        };
        vector operator  + (vector iv)
        {
                return vector(x + iv.x,  y + iv.y);
        };
        vector operator  - (vector iv)
        {
                return vector(x - iv.x, y - iv.y);
        };
};
void main()
{
        vector v1(11);
        v1.print();
        vector v2(44);

        v2        vector v3  =  v1  +  v2;
        v3.print();
}

copy with pointer increment

 

/*
 * uses increment on a pointer to ;
 * copy one string to another
 */
#include <iostream>

using namespace std;
void main()
{
        void strcopy(char  *  in,  char  *  out);

        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        char         * mystr  =   "This is my first string";
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

        char mystr2[80];
        strcopy(mystr, mystr2);
        cout  <<  mystr2  <<  endl;
}

void strcopy(char  * in,  char  * out)
{
        while (*in)
        {
                  * (out++)   =   * (in++);
                 
        }
}

new and delete (using a destructor)

 

#include <iostream>

#include <cstring>

using namespace std;
class String
{
private:
        char         * str;
public:
        String(char  *  s)
        {
                int len  =  strlen(s);
                str  =  new char[len  +  1];
                strcpy(str, s);
        };
        char         *
         value()
         
        {
                return str;
        };

        ~String()
        {
                cout  <<   "destructing: "  <<  endl;
                 delete []  str;
        };
};
void main()
{
        String mys  =   "This is a sample string that will be trimmed down to size";
        cout  <<  mys.value()   <<  endl;
}

 

Pure Virtual

#include <iostream>
#include <string>
using namespace std;

class clsmybase{
protected:
        string name;
public:

        string getname() {return name;};
        virtual float getdata() = 0;
        virtual bool getenrolled() = 0;


};

class student: public clsmybase{
private:
        float gpa;
        bool enrolled;
public:
        student(string name,float gpa,bool enrolled)
        {clsmybase::name = name;
        this->gpa=gpa;
        this->enrolled=enrolled;};
        float getdata(){return this->gpa;};
        bool getenrolled(){return this->enrolled;};

};

class prof: public clsmybase{
private:
        float salary;
        bool tenured;
public:
        prof(string name, float salary, bool tenured)
        {
                clsmybase::name = name;
                this->salary = salary;
                this->tenured = tenured;};
                float getdata(){return this->salary;};
                bool getenrolled(){return this->tenured;};

};

void Disp(clsmybase * s)
{
cout << s->getname() << " " << s->getdata() << " " << s->getenrolled()<< "\n";


}

void main(){
student * bob = new student("bobby",3.2F,true);
prof * bill = new prof("prof billy",100000.0F,true);
Disp(bob);
Disp(bill);

cin.get();




};

 

Another Inheritance example with a friend operator overload. Operator overload is for vector addition.

 

#include "stdio.h"

class vector1{
protected:
double x;
public:
        vector1(double ix){x=ix;}
        vector1(){x=0;};
        void tostring(){
                printf("(%f)\n",x);
        };
};

class vector2: public vector1{
protected:
double y;
public:
vector2(double ix,double iy) : vector1(ix){y=iy;};
vector2():vector1(){y=0;};
void tostring(){
        printf("(%f,%f)\n",x,y);
};

friend vector2 operator + (vector2 v1, vector2 v2){
return vector2 (v1.x + v2.x, v1.y + v2.y);
};
};

void main()
{

        vector2 v2(-1,6);
        vector2 v3(-3,8);
        vector2 v1 = v2+v3;
        v1.tostring();

};

sort using classes and **

/*
 * program to allow entered data ;
 * and sort it, using array of pointers
 */
#include <iostream>

#include <string> 

using namespace std;

/* employee class */
class empl
{
private:
        string name;
public:

        /* constructor */
        empl(string iname)
        {
                name  =  iname;
        };

        /* method for accessing private member, name */
        string getname()
        {
                return name;
        };
};
void main()
{
        void bsort(empl ** pp, int n);

        empl         * emplptr[100];
        int n  =   - 1;
        string name;
        do 
        {
                n++;
                cout  <<   "Enter a name (quit to quit) " ;
                 cin  >>  name;
                if (name  !=   "quit")
                {
                        emplptr[n]   =  new empl(name);

                        /*
                         * cout << emplptr[n]->getname();
                         */
                }
        }

        while(name  !=   "quit");
        n--;
        cout  <<   "Original List"  <<  endl;
        for (int j  =  0;  j <= n;  j++)
        {
                cout  <<  emplptr[j]->getname()   <<  endl;
        };
        cout  <<   "Sorted List"  <<  endl;
        bsort(emplptr, n);
        for (int j = 0; j <= n; j++)
        {
                cout <<  emplptr[j]->getname() << endl;
        };
        cin.get();
        cin.get();
};
void bsort(empl ** pp, int n)
{
        void order(empl **, empl **);
        for (int j  =  0;  j <= n;  j++)
        {
                for (int k  =  j + 1;  k <= n;  k++)
                {
                        order(pp + j, pp + k);
                };

                /* end k */
        };

        /*  end j */
};

/*
 =======================================================================================================================
    pp1 and pp2 are pointers to arrays of empl ;
    argument accepts pointers to pointer arrays
 =======================================================================================================================
 */
void order(empl ** pp1,  empl ** pp2)
{

        /*
         *  use > as you would for numbers;
         * * use -> for accessing members when using pointer
         */
        if ((*pp1)->getname()   >  (*pp2)->getname())
        {

                /* pp1 is greater, thus, set a temp pointer to point to pp1 */
                empl        * tmpptr  =   * pp1;

                /* set pp1 to point to pp2 (pp2 is smaller, therfore earlier in list */
                *pp1  =   * pp2;

                /* set pp2 to point to temp */
                *pp2  =  tmpptr;
        };
};

new class vector3, friend operator overload + and a general 'sum' template which adds objects. #include "stdio.h"
#include <iostream>
using namespace std;

class vector3
{
        public:
             double a,b,c;
             vector3(double ia,double ib, double ic){a=ia;b=ib;c=ic;};
             void tostring(){printf("(%f,%f,%f)\n",a,b,c);};
friend vector3 operator +(vector3 v1, vector3 v2)
{
return vector3(v1.a+v2.a,v1.b+v2.b,v1.c+v2.c);
};
};


template <class V> V sum(V &a, V &b)
{
        return a + b;
};




void main()
{
vector3 v1(1,1,1);
vector3 v2(2,5,-1);
(v1+v2).tostring();
vector3 v3=sum(v1,v2);
v3.tostring();

}

binary i/o

 

#include <fstream>
#include <iostream>
using namespace std;
const int                NUM = 26;
double                   buffer[NUM];


void main()
{
        
for(int j = 0; j < NUM; j++)
        {
                *(buffer + j) = (
double) j;
        };

        ofstream        buffout(
"buffer.dat", ios::binary);
        buffout.write(reinterpret_cast < 
char * > (buffer), NUM * sizeof(double));
        buffout.close();
        cout << 
" File Written to " << endl;
        
for(int j = 0; j < NUM; j++)
        {
                *(buffer + j) = (
double0;
        };

        ifstream        buffin(
"buffer.dat", ios::binary);

        buffin.read(reinterpret_cast < 
char * > (buffer), NUM * sizeof(double));
        
for(int j = 0; j < NUM; j++)
        {
                cout << j << 
"," << *(buffer + j) << endl;
                
if(*(buffer + j) != j)
                {
                        cerr << 
"Wrong!";
                };
        };
        cout << 
"Info read correctly" << endl;
        cin.get();
};




};

 

4/2007

kurt bingham 2008

  Home