CSE 109 Test 2  Wednesday  12 April 2006
>>>>>>>>>>>>>>>>SUGGESTED ANSWERS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1. Write a function strcopy() that safely returns the copy of a string. If
we have declared  char *f,ch[]="A string"; then a call to strcopy() might
be    f=strcopy(ch);
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
char * strcopy(char *ch)
{char *temp;
 if(ch==NULL)
   return NULL;
 temp=new char[strlen(ch)+1];
 if(temp==NULL)
   {cerr<<"Error: Heap overflow\n";
    exit(1);
   }
 strcpy(temp,ch);
 return temp;
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
2.  Write MACH1 code that would correspond to the MCASM program below.
    read x
    jump neq two
    write x
two halt
    end
Hint: Recall the mach1 code: read(0), write(1), load(2), store(3),
clear(4), add(5), sub(6), mult(7), div(8), addi(9), subi(10), multi(11),
divi(12), lte(13), gte(14), halt(15).
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    0  0   [0]  read; no need to store x for this program
   13  3   [1]  if lte skip next line
   14  6   [2]  must be > so jump to two
   14  5   [3]  if gte skip next line
   13  6   [4]  must be < so jump to two
   1   0   [5]  write
   15  0   [6]  this is "two"
   E
   Note: A solution that stores the value in x and retrieves it is okay.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

3.  Write a program that writes out the first line of every file
that is both listed on the command line and exists.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#include <iostream>
#include <fstream>
using namespace std;
int main(int ct, char **arg)
{ifstream f;
 char ch;
 for(int j=1; j<ct; j++)
   {f.open(arg[j]);
    if(f.good())
     {f.get(ch);
      while(f.good() && ch!='\n')
       {cout<<ch;
        f.get(ch);
       }
      cout<<endl;
     }
    f.clear();   //in case !f.good()
    f.close();
   }
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4.  Add a function display() to the class A below and write a subclass B of
class A.  The only purpose of class B is to override the function
display() in class A (and class B should do nothing more than that). If we
have    A a(2,4); B b(2,4); then a.display()  produces   2, 4
while b.display() produces [2,4]. Further, b.x(), should produce  -->[2,4]
class A
 {public:
   A(int a=0, int b=0):s(a),t(b){}
   void x(){cout<<"-->"; display();}
  private:
    int s,t;
 };
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
in the public section of class add:
  virtual void display();

class B:public A
 {public:
   B(int a=0, int b=0);
   void display();
 };

void A::display(){cout<<s<<", "<<t;}

B::B(int a, int b):A(a,b){}

void B::display(){cout<<"["; A::display(); cout<<"]";}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
