// ========================================================================== // $Id: readfile.cpp,v 1.1 2016/11/21 17:38:46 jlang Exp $ // CSI2372 example Code for lecture 9 // ========================================================================== // (C)opyright: // // Jochen Lang // EECS, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.eecs.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@eecs.uottawa.ca // ========================================================================== // $Log: readfile.cpp,v $ // Revision 1.1 2016/11/21 17:38:46 jlang // Created simple file parser example. // // ========================================================================== #include #include #include #include using namespace std; #if 0 // Separate insertion and extraction as templates template class Point2D; template istream& operator>>( istream&, Point2D& ); template ostream& operator<<( ostream&, const Point2D& ); template class Point2D { T x; T y; public: friend istream& operator>> <>( istream&, Point2D& ); friend ostream& operator<< <>( ostream&, const Point2D& ); }; template istream& operator>> ( istream& is, Point2D& p ) { char tmp; is >> tmp >> p.x >> tmp >> p.y >> tmp; if ( is.fail() ) { p = Point2D(); } return is; } template ostream& operator<< ( ostream& os, const Point2D& p ) { os << "( " << p.x << ", " << p.y << " )"; } #else // Compact with insertion and extraction as non-templates template class Point2D { T x; T y; public: friend istream& operator>> ( istream& is, Point2D& p ) { char tmp; is >> tmp >> p.x >> tmp >> p.y >> tmp; if ( is.fail() ) { p = Point2D(); } return is; } friend ostream& operator<< ( ostream& os, const Point2D& p ) { os << "( " << p.x << ", " << p.y << " )"; } }; #endif int main() { string fn{"geom2D.txt"}; ifstream in(fn); if (!in) { cerr << "Could not open file: " << fn << endl; return -1; } string line, token; // Get a line while (getline(in, line)) { istringstream streamLine(line); cout << "Got line: " << line << endl; // Get individual white space separated tokens while ( streamLine >> token ) { // Process token if ( token == "point" ) { Point2D p; streamLine >> p; cout << "Point coordinates: " << p << endl; break; } if ( token == "line" ) { Point2D pS, pE; streamLine >> pS >> pE; cout << "Line segment: " << pS << " " << pE << endl; break; } if ( token == "triangle" ) { Point2D pA, pB, pC; streamLine >> pA >> pB >> pC; cout << "Triangle: " << pA << " " << pB << " " << pC << endl; break; } if ( token == "end" ) break; cerr << "Unknown token!" << endl; } if ( token == "end" ) break; } }