/* testfile3.cpp CIS 150 6/10/2008 David Klick This program demonstrates the use of a repetition construct to read a file of unknown length. */ #include #include using std::cin; using std::cout; using std::ofstream; using std::ifstream; void cont(); int main() { int n; // open a file for writing cout << "Opening output file\n"; ofstream outfile("datafile3.txt"); // display error and exit if file didn't open if (!outfile) { cout << "Error: could not open output file.\n"; cont(); return 1; } // write some data out to file cout << "Writing data to file\n"; for (n=11; n<40; n=n+2) { outfile << n << '\n'; } // done processing - close file outfile.close(); cout << "File created\n"; // open the file we created for reading cout << "Opening input file\n"; ifstream infile("datafile3.txt"); // display error and exit if file didn't open if (!infile) { cout << "Error: could not open input file.\n"; cont(); return 2; } // read all data from the file and display it // - a loop is used here because the number of // records to be read is unknown cout << "Reading data from file\n"; while (infile >> n) { cout << n << '\n'; } // done processing - close file infile.close(); cout << "Program done\n"; cont(); return 0; } void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); }