A solution to Problem X (1 point)


Here is a solution to Problem X. This program demonstrates several things.

Good things
  • The use of assert(). This is the greatest command you can ever use. Use it lots. It will become your friend.
  • Simple I/O in C++
  • Not so good things
  • Breaking out of loops in the middle. In an ideal world you'd like to do something like:
    	        while(condition){
    	           process...
    	        }
    	  
  • What would happen in the file existed, but was empty? What are we assuming about x1 and x2? (change int x1,x2 to int x1=1,x2; and find out).
  • asserting file I/O. If you were writing something that was to be more robust, you would:
    	        if(!infile){
    	           // output a warning
    	        }
    	  

  • // Problem X solution by Stuart Inglis
        
    #include < iostream.h >
    #include < fstream.h >
    #include < assert.h >
    
    void main(void)
    {
      int x1,x2;
    
      ifstream infile("PROBLEMX.DAT", ios::in);
      assert(infile);
    
      while(1){
        infile >> x1 >> x2;
        if(x1 == 0 && x2 == 0) break;
        cout << x1+x2 << endl; 
      }
    }