C++


Templates - for getting started with C++
Objects - an illustration of how to use objects
  • (see also, MatrixTools)
    Examples - to reference

    A Typical Header:
    #include <iostream>
    #include <stdlib.h>
    #include <math.h>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <ctime>
    using namespace std;
    int main(int argc, char *argv[]){
    ...
    return 0;
    }

    To on compile on ldas-pcdev2 with libraries:
    FRVER=v6r24
    gcc -O -fexceptions -fPIC extras/example.c ${FRVER}/src/libFrame.a -I${FRVER}/src -lm -o bin/example

    I/O
    To control precision of cout statements: cout.precision(10);
    To control precision of other streams: outfile.precision(4);
    To force numbers into scientific notation: cout.setf(ios::scientific);
    To force the "e" in 10e03 to be capitalized: cout.setf:(ios::uppercase);
    To turn off these options follow this syntax: cout.unsetf(ios::left);
    To cout a tab: cout << "\t"; (Makefile's prefer tabs to spaces)

    To convert char to int:
    int Q=atoi(argv[4]);   (converts command line asci to an integer)
    char hh='4';
    int zz=atoi(&hh);   (in thise case, use a reference operator)

    Functions for other asci conversions: atof (floats), itoa (reverse)...
    std::string itoa(int aV){
    char buf[128];
    sprintf(buf, "%d", aV);
    return buf;
    }

    sprintf example:
     char buf[128]; string x="cat"; string y="doughnuts"; int i=2;
     sprintf(buf, "the %s ate %d %s",x.c_str(),i,y.c_str()); 
    sprintf flags:
     char   %c
     float  %f
     string %s
     int    %d
    
    To convert a string to a const *char:
    string x=argv[1]; string y=".log"; string z=x+y;
    ifstream lfile(z.c_str());
    //z.c_str() is a const *char

    To convert string to double
      #include <sstream>
      string x=argv[3];
      double a;
      std::istringstream i(x); i >> a;

    Manipulating Strings
    to cut/remove/erase letters from the end of a string:
    string x="file.data";
    x.erase(x.length()-5,x.length());
    Now x="file"
    ...from the beginning:
    string prefix="dec-78";
    prefix.erase(0,3);
    Now prefix="-78".
    to create an array of strings: std::string x[]={"sk1/ostop.mct", "sk1/othru.mct", "sk1/oshower.mct"};

    Converting integers to doubles:
    int N=10;
    double x=(double)N+3.
    Converting doubles to integers:
    double a=1.3;
    int b=(int)a; //b has a value of 1 because we round down for positive ints
    a=-1.3;
    b=(int)a; //b has a value of -1 beacuse we round up for negative ints

    random numbers:
    random int on [1,Max]: int P(int MAX){return(rand()%MAX+1);}
    random double on (0,1): double P(){return(-(double)rand()/(double)(RAND_MAX+1));

    Logical Operators for Conditionals: and &&, or ||
    Not to be confused with Bitwise Operators: e.g. intersect=Trigger&Mask or union=1|x; or notx=~x;

    Using a void function:
    void spline(float x[],float y[],int n,float yp1,float ypn,float y2[]){
    if (yp1 > 0.99e30)
    y2[1]=u[1]=0.0;
    ...
    }
    int main(int argc, char *argv[]){
    spline(x,y,N,yp1,ypn,y2);
    ...
    }

    using void functions with pointers:
    void radec(double phi, double theta, double lst, double *ra, double *dec) {
      cout << phi << endl;
      *ra=1;
    }
    int main() {
      . . .
      radec(phi,theta,t,&r,&d)
    }

    passing pointers to functions (functions of functions), and arrays of arbitrary size:
    void ksone(float data[], float (*func)(float)) {
      cout << data[3] << endl;
      float ff=(*func)(data[3]);
    }

    reading in a file:
    #include <fstream>
    int main(int argc, char *argv[]){
      ifstream infile(argv[1]);
      if(!infile){
        cout << "Error: Can't locate input file." << endl;
        exit(1);
      }
      while(!infile.eof())
        infile >> Trg >> t1 >> t2 >> t3;
      }
    infile.close();

    To determine if a file exists: ifstream data("file.dat");
    if(data.fail()){cout << "file.dat does not exist" << endl;}

    defining a macro:   (an arcane holdover from C)
      #define MAX(a, b) ((a) > (b) ? (a) : (b))
    Is a greater than b? If so, the value of MAX is a. If not, the value is b.
    conditional compiling:
    #define SKX 1 
    int main(int argc, char *argv[]) { 
    ... 
    #if SKX==1 
            tP=pt(tsk1,24,0,24); 
    #endif 

    to pause: cin.get();

    a generalized for loop: for(start; test; do;){}
    start is executed at the beginning of the loop.
    test is evaluated before every iteration and the code loops again only if it evaluates true.
    do is evaluated at the end of each iteration.


    to define a constant array of doubles:
    const double S[20]={
      0,1,2,3,4,5,6,7,8,9,
      0,1,2,3,4,5,6,7,8,9
    };
    
    const double test[3][3]={
      { 0,  0,  0},
      { 0,  0,  1},
      { 0,  0,  0}
    }; 
    
    const double test3d[][2][3]={
      {
        {1,2,3},       //[0][i][j]
        {3,4,6}
      },
      {
        {11,12,13},    //[1][i][j]
        {13,14,16}
      },
      {
        {21,22,23},
        {23,24,26}
      },
      {
        {31,32,33},
        {33,34,36}
      }
    };
    to execute a shell command from within a C++ executable: system("ls");
    Note: the command issued via "system" must be a const char.
    to execute a shell command that depends on C++ variables:
    string x;
    ...
    char buffer[50];
    sprintf(buffer, "wc %s",x.c_str());
    system(buffer);
    issues the command: "wc x" for whatever value of x
    To access an environmental variable: char *homestring=getenv("HOME");

    To test if a variable you are using, x, is infinite or nan:
    examine the values of isnan(x) and finite(x).

    Are two strings the same? if(strcmp(x,y)==0){ cout << "x and y are the same: non-zero values tell you which character is different!"; }


    To print something to screen when piping to /dev/null syserror(0, "Starting up\n");

    Back to Resources