#include #include #include #include "CPstring.h" #include "vector.h" // author: Owen Astrachan // date : May 12, 1996 // // reads a file of titles, illustrates use of strstream // to parse input // // input file: a sequence of lines, each line is a title // (collection of words) // // output: # of words in each title (line) followed by title // struct Title { Vector words; // collection of words int numWords; // # of words in collection }; ostream & operator << (ostream & os, const Title & title) // postcondition: title printed to stream os { int k; cout << " words = " << title.numWords << " : "; for(k=0; k < title.numWords; k++){ os << title.words[k] << " "; } return os; } int main(int argc, char * argv[]) { Vector library(200); // room for 200 titles int numTitles = 0; // count of # titles string filename = "default"; // where is data stored string buffer; // for each line of input string word; // for each word from a line ifstream input; // stream for input if (argc > 1) // argument passed to program { filename = argv[1]; } input.open(filename.c_str()); if (input.fail()) { cout << "could not open file " << filename << endl; exit(1); } while (getline(input,buffer)) { istrstream parseline(buffer.c_str()); int count = 0; while (parseline >> word) // count # of words on a line { count++; } library[numTitles].numWords = count; // store # words library[numTitles].words.resize(count); // exact size for vector parseline.clear(); // clear for re-reading parseline.seekg(0); // reset to beginning count = 0; // reset count while (parseline >> word) { library[numTitles].words[count] = word; count++; } cout << library[numTitles] << endl; numTitles++; } cout << endl << "# titles = " << numTitles << endl; return 0; }