/* testfile2.cpp CIS 150 6/3/2008 David Klick This program demonstrates some simple file I/O techniques. This is a working version of testfile1.cpp. */ #include #include using std::cin; using std::cout; using std::ofstream; using std::ifstream; void cont(); int main() { // create some data to write to file int n = 17; double x = 37.887; bool flag = true; // open a file for writing cout << "Opening output file\n"; ofstream outfile("datafile1.txt"); // display error and exit if file didn't open if (!outfile) { cout << "Error: could not open output file.\n"; return 1; } // write some data out to file // - The problem with writing and reading has been // fixed by putting a delimiter after each value // as it is written. cout << "Writing data to file:\n"; cout << "n = " << n << '\n'; cout << "flag = " << flag << '\n'; cout << "x = " << x << '\n'; outfile << n << '\n'; outfile << flag << '\n'; outfile << x << '\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("datafile1.txt"); // display error and exit if file didn't open if (!infile) { cout << "Error: could not open input file.\n"; return 2; } // read some data from the file and display it cout << "Reading data from file\n"; infile >> n >> flag >> x; cout << "n = " << n << '\n'; cout << "flag = " << flag << '\n'; cout << "x = " << x << '\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(); } /* Sample run: Opening output file Writing data to file: n = 17 flag = 1 x = 37.887 File created Opening input file Reading data from file n = 17 flag = 1 x = 37.887 Program done Press enter to continue... */