Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition,
© 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3
Figure 5-1 Demonstration of file I/O |
/*-------------------------------------------------------------------------- Read numeric data stored in a file, compute the minimum, maximum, and average of the numbers, and write these statistics to an output file. Input(keyboard): names of the input and output files Input(file): a sequence of numeric values Output(file): a count of the values, the minimum value, the maximum value, and the average value --------------------------------------------------------------------------*/ #include <iostream> // cin, cout #include <fstream> // ifstream, ofstream #include <string> // string, getline() #include <cassert> // assert() #include <cfloat> // DBL_MIN and DBL_MAX using namespace std; int main() { cout << "This program computes the number, maximum, minimum, and\n" "average of an input list of numbers in one file,\n" "and places its results in another file.\n\n"; // ----------- Input Section ----------------------------------- cout << "Enter the name of the input file: "; string inputFileName; getline(cin, inputFileName); // get name of input file // open an input stream ifstream fin; // to the input file, fin.open(inputFileName.data()); // establish a connection, assert( fin.is_open() ); // and check for success int count = 0; // number of values double reading, // value being processed maximum = DBL_MIN, // largest seen so far minimum = DBL_MAX, // smallest seen so far sum = 0.0; // running total for (;;) // loop: { fin >> reading; // read a value from file if ( fin.eof() ) break; // if eof, quit count++; // update: count, sum += reading; // sum, if (reading < minimum) minimum = reading; // minimum, if (reading > maximum) maximum = reading; // maximum } // end loop fin.close(); // close the connection // ------------ Output Section --------------------------------- cout << "Enter the name of the output file: "; string outputFileName; getline(cin, outputFileName); // open an output stream ofstream fout(outputFileName.data()); // to the output file, // establish a connection, assert( fout.is_open() ); // and check for success // write results to file fout << "\n--> There were " << count << " values"; if (count > 0) fout << "\n ranging from " << minimum << " to " << maximum << "\n and their average is " << sum / count << endl; fout.close(); // close the stream cout << "Processing complete.\n"; } |
Figure 5.2 String Stream Demo |
#include <iostream> #include <fstream> #include <iomanip> #include <cassert> #include <sstream> using namespace std; int main() { string date = "U.S. independence: July 4, 1776"; istringstream istr(date); string word1, word2, month; int day, year; char comma; istr >> word1 >> word2 >> month >> day >> comma >> year; cout << "Contents of string stream istr, one word per line:\n" << word1 << '\n' << word2 << '\n' << month << '\n' << day << comma << '\n' << year << '\n' << endl; const int Y2K = 1999; ofstream outfile("file5-2.out"); assert(outfile.is_open()); ostringstream ostr; ostr << word1 << "bicentennial: " << month << setw(2) << day << ", " << year + 200 << endl; cout << "Contents of string stream ostr:\n" << ostr.str(); outfile << ostr.str(); } |
Figure 5.3A Text Editor Declaration |
/*-- TextEditor.h --------------------------------------------------------- This header file defines the data type TextEditor for editing text files. Basic operations are: Constructor: Construct a TextEditor object for given files run() Run the editor showMenu(): Display the menu of editing "hot keys" insert(): Insert a string in a line of text erase(): Remove a string from a line of text replace(): Replace a string by another string in a line of text next(): Output edited line and get next line to edit quit(): Wrap up editing -------------------------------------------------------------------------*/ #include <iostream> #include <string> #include <fstream> class TextEditor { public: /******** Function Members ********/ TextEditor(string inputFile, string outputFile); /*---------------------------------------------------------------------- Construct a text editor for files named inputFile and outputFile. Precondition: inputFile is the file to be edited. Postcondition: outputFile contains the edited text. ----------------------------------------------------------------------*/ void run(); /*---------------------------------------------------------------------- Run the editor. Precondition: None. Postcondition: Text from inputFile has been edited and output to outputFile. ----------------------------------------------------------------------*/ void showMenu(); /*---------------------------------------------------------------------- Display menu of editing commands. Precondition: None. Postcondition: Menu has been output to cout. ----------------------------------------------------------------------*/ void insert(string str1, string str2); /*---------------------------------------------------------------------- Insert a string into a line of text. Precondition: None. Postcondition: str1 has been inserted before str2 in myLine if str2 is found in myLine; otherwise, myLine is unchanged. ----------------------------------------------------------------------*/ void erase(string str); /*---------------------------------------------------------------------- Remove a string from a line of text. Preconditions: None. Postcondition: str has been removed from myLine if str is found in myLine; otherwise, myLine is unchanged. ----------------------------------------------------------------------*/ void replace(string str1, string str2); /*---------------------------------------------------------------------- Replace one string with another in a line of text. Precondition: None. Postcondition: str1 has been replaced with str2 in myLine if str1 is found in myLine; otherwise, myLine is unchanged. -----------------------------------------------------------------------*/ void next(); /*---------------------------------------------------------------------- Move on to next line of text to edit. Precondition: None. Postcondition: String that was in myLine has been output to myOutstream and a new line read from myInstream into myLine. ----------------------------------------------------------------------*/ void quit(); /*---------------------------------------------------------------------- Quit editing. Precondition: None. Postcondition: String that was in myLine has been output to outputFile and any lines remaining in inputFile have been copied to outputFile. ----------------------------------------------------------------------*/ private: /******** Data Members ********/ ifstream myInstream; ofstream myOutstream; string myLine; }; |
Figure 5.3B Text Editor Definitions |
/*-- TextEditor.cpp ------------------------------------------------------- Contains definitions of the function members of class TextEditor. -------------------------------------------------------------------------*/ #include <iostream> #include <string> #include <cctype> using namespace std; #include "TextEditor.h" //--- Utility function to eat spaces from cin void eatBlanks() { char blank; while (cin.peek() == ' ') cin.get(blank); } //--- Definition of constructor TextEditor::TextEditor(string inputFile, string outputFile) { myInstream.open(inputFile.data()); myOutstream.open(outputFile.data()); if (!myInstream.is_open() || !myOutstream.is_open()) { cerr << "Error in opening files."; exit(-1); } } //--- Definition of run() void TextEditor::run() { showMenu(); cout << "Enter an editing command following each prompt >\n\n"; getline(myInstream, myLine); cout << "TEXT: " << myLine << endl; char command; string str1, str2; for (;;) { if (myInstream.eof()) break; cout << '>'; cin >> command; cin.ignore(1, '\n'); switch(toupper(command)) { case 'I' : eatBlanks(); getline(cin, str1); cout << "Insert before what string? "; getline(cin, str2); insert(str1, str2); break; case 'D' : eatBlanks(); getline(cin, str1); erase(str1); break; case 'R' : eatBlanks(); getline(cin, str1); cout << "With what? "; getline(cin, str2); replace(str1, str2); break; case 'N' : next(); break; case 'Q' : quit(); break; default : cout << "\n*** Illegal command ***\n"; showMenu(); cout << "TEXT:" << myLine << endl; }// end of switch if (!myInstream.eof()) cout << "TEXT: " << myLine << endl; } cout << "\n*** Editing complete ***\n"; } //--- Definition of showMenu void TextEditor::showMenu() { cout << "Editing commands are:\n" " I str: Insert string str before another string\n" " D str: Delete string str\n" " R str: Replace string str with another string\n" " N : Get next line of text\n" " Q : Quit editing\n"; } //--- Definition of insert() void TextEditor::insert(string str1, string str2) { int position = myLine.find(str2); if (position != string::npos) myLine.insert(position, str1); else cout << str2 << " not found\n"; } //--- Definition of erase() void TextEditor::erase(string str) { int position = myLine.find(str); if (position != string::npos) myLine.erase(position, str.length()); else cout << str << " not found\n"; } //--- Definition of replace() void TextEditor::replace(string str1, string str2) { int position = myLine.find(str1); if (position != string::npos) myLine.replace(position, str1.length(), str2); else cout << str1 << " not found\n"; } //--- Definition of next() void TextEditor::next() { myOutstream << myLine << endl; getline(myInstream, myLine); cout << "\nNext line:\n"; } //--- Definition of quit() void TextEditor::quit() { myOutstream << myLine << endl; for (;;) { getline(myInstream, myLine); if (myInstream.eof()) break; myOutstream << myLine << endl; } } |
Figure 5.3C Text Editor Driver Program |
/*-- Fig4-3.cpp ----------------------------------------------------------- Driver program for TextEditor class. It gets the name of a file to be edited from the user, appends ".out" for the output file, builds a TextEditor object editor for these files, and sends it the run() message. -------------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; #include "TextEditor.h" int main() { string inFileName, outFileName; cout << "Enter the name of the input file: "; getline(cin, inFileName); outFileName = inFileName +".out"; cout << "The output file is " << outFileName << "\n\n"; TextEditor editor(inFileName, outFileName); editor.run(); } |
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|
Figure |
|