// CSE143 Sp01 Homework 2 Sample Solution // hw2sol.cpp - main program // HP 4/01 #include #include #include using namespace std; #include "placelist.h" #include "location.h" // symbolic constants const string EOF_MARKER = "."; // place name that marks end of data file const string QUIT_MARKER = "."; // input value entered by user to stop program // Get file name from user and read place data from that file, storing // it in places. Return true if successful, otherwise return false. bool readPlaceList(PlaceList &places) { string fileName; // data file name double x, y; // current location and place name from file string name; // Get file name from user cout << "Enter file name: "; cin >> fileName; // Attempt to open file; quit if unsuccessful ifstream data(fileName.c_str()); if (!data) { return false; } // read data from file data >> x >> y >> name; while (name != EOF_MARKER) { places.add(x, y, name); data >> x >> y >> name; } return true; } // If name is found in places, return true; otherwise print // a suitable message and return false. bool checkPlace(PlaceList &places, string name) { if (places.contains(name)) { return true; } else { cout << "Never heard of " << name << endl; return false; } } // Read pairs of place names and report distance and direction from // first name of each pair to the second void answerQueries(PlaceList &places) { string origin; // first name of a pair string destination; // second name of a pair bool origFound; // = "origin found in places" bool destFound; // = "destination found in places" Location origLoc; // Locations of origin and destination Location destLoc; double distance; // distance from origin to destination for(;;) { // read origin and quit if it is the "." marker cout << "\nEnter start location: "; cin >> origin; if (origin == QUIT_MARKER) { cout << "Bye" << endl; return; } // read destination cout << "Enter destination: "; cin >> destination; // check whether origin and destination are in places, // and print a suitable message if they are not there origFound = checkPlace(places, origin); destFound = checkPlace(places, destination); // if both places are known, report distance and direction // from origin to destination if (origFound && destFound) { origLoc = places.locationOf(origin); destLoc = places.locationOf(destination); distance = origLoc.distanceTo(destLoc); if (distance == 0.0) { cout << "Distance from " << origin << " to " << destination << " is " << distance << " miles" << endl; } else { cout << destination << " is " << distance << " miles " << origLoc.directionTo(destLoc) << " of " << origin << endl; } } } } // main program int main() { PlaceList places; // list of place names and locations bool success; // = "input file read successfully" success = readPlaceList(places); if (!success) { cout << "Unable to read input file" << endl; return 1; } answerQueries(places); return 0; }