// Author: Keith Shomper // Date: 10/20/03 // Putpose: Demonstrates how to open and close files for input and output // by counting the words of an input file #include #include using namespace std; int main() { string s; // For reading in words string filename; // For specifying a file name ifstream in; // Input file stream ofstream out; // Output file stream int words = 0; // For keeping track of the number of words in the file cout << "Please enter a file to open: "; cin >> filename; // open the input file in.open(filename.c_str()); if (in == 0) { cerr << "Error opening file " << filename << ". Exiting ....." << endl; exit(1); } // get a word in >> s; // while there are characters to read while (!in.eof()) { // increment the word count words++; // get a word in >> s; } // build the output filename filename += ".cnt"; // output the results out.open(filename.c_str()); out << "There are " << words << " words in file " << filename.substr(0, filename.size()-4) << endl; // close input and output files in.close(); out.close(); return 0; }