CSCI 2270 Computer Science 2: Data Structures
Fall 2003
Karl Winklmann

Reading from a text file, sorting objects

Thursday, September 11, 2003

 


Previous page | Next page | Latest page | Schedule and syllabus | Home Page | Programs | Table of contents | News archive | Dora

These are more code fragments discussed in class.

Reading from a text file

I added some detail to the code fragment below compared to when it was first posted.
#include <fstream>
#include <iostream>
#include <string>

 ...

string testFileName;
ifstream testFile;
 ...

cin >> testFileName;
testFile.open (testFileName.c_str ());
if (!testFile)
    // for some reason the file is not available
else // successful open
{
   while (testFile.peek () != EOF)
   {
       testFile >> x >> y >> z >> dx >> dy >> dz;
       // do what needs to be done with that input
   }
   testFile.close ();
}

Sorting an array of objects

Sorting is easy ...
sort (canvas.elements, canvas.elements + canvas.n);
but you need to #include <algorithm> and provide a less-than operator
bool operator< ( const MovingObject& mo1, const MovingObject& mo2 )
{
    return mo1.z > mo2.z; // yes, backwards (depending on your conventions
                             //   about the coordinate system)
}
which should be a friend of the MovingObject class.  


© 2003 Karl Winklmann 3:08 PM, Tuesday, December 16, 2003