//assume the following declarations ifstream inStr; inStr.open("myfile"); int howMany = 0; int dataValue; // code to read data values from a file and count howmany there are // METHOD 1 -- using a pre-test loop with an priming read inStr >> dataValue; while (!inStr.eof()) { howMany++; inStr >> dataValue; } // METHOD 2 -- using a post-test loop and an if statement do { inStr >> dataValue; if (!inStr.eof() howMany++; } while (!inStr.eof()); // METHOD 3 -- using an infinite loop and break while (true) { inStr >> dataValue; if (inStr.eof()) break; // exit on end of file howMany++; } // METHOD 4 -- using the value returned by >> // this one is not exactly the same as the other three since // it will stop if invalid data is read not just on end of file while (inStr >> dataValue) howMany++; //**************************************************************************** // function to ask user for a file name and attach to an ifstream // // parameter usage : inStr -- exports the stream attached // // Post-conditions -- inStr is attached to a file and is ready for extractions // -- the cin stream is cleared of data //**************************************************************************** void openIn(ifstream& inStr) { string filename; cout << "Enter the name of the file -- "; while (true) { cin >> filename; inStr.open(filename.c_str()); if (inStr) break; // successful attachment // not successful clrStream(); // clear all characters from the cin stream cout << "Unable to open file " << filename << " Reenter filename -- "; } clrStream(); // clear to the end of the line }