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 #include using namespace std; int main(int ct, char **arg) {ifstream f; char ch; for(int j=1; j[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<