1: //readwrite.cpp 2: //To test RTTI (run-time type identification). 4: #include <iostream> 5: #include <fstream> 6: #include <string> 7: #include <typeinfo> 8: using namespace std; 11: void DisplayProgramInfo(); 12: /**< 13: Display the program description. 14: @pre None. 15: @post The program description has been displayed, 16: preceded by a blank line and followed by a pause. 17: */ 20: void ReadData 21: ( 22: istream& inStream, //in 23: string& someString //out 24: ); 25: /**< 26: Reads a single word from an input stream. 27: @return void 28: @param inStream 29: @param someString 30: @pre inStream exists and is open. 31: @post 32: - someString contains a word from inStream. 33: - inStream is still open. 34: */ 37: void WriteData 38: ( 39: ostream& outStream, //inout 40: const string& someString //in 41: ); 42: /**< 43: Writes a single word to an output stream. 44: @return void 45: @param outStream 46: @param someString 47: @pre 48: - outStream exists and is open. 49: - someString has been initialized. 50: @post 51: - Value in someString has been written to outStream. 52: - outStream is still open. 53: */ 55: int main() 56: { 57: DisplayProgramInfo(); 59: string secretWord; 61: cout << endl; 62: ifstream inFile("readwrite.in");; 63: ReadData(inFile, secretWord); 64: inFile.close(); inFile.clear(); 66: WriteData(cout, secretWord); 67: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 68: cout << endl; 70: ReadData(cin, secretWord); 71: ofstream outFile("readwrite.out"); 72: WriteData(outFile, secretWord); 73: outFile.close(); outFile.clear(); 74: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 75: } 78: void DisplayProgramInfo() 79: { 80: cout << "\nThis program reads data from a file called readwrite.in, " 81: "and then writes it\nout to the screen. Next, it reads the same " 82: "kind of data from the keyboard\nand writes it out to a file " 83: "called readwrite.out." 85: "\n\nAt the moment, in both cases, the input data is just a " 86: "single word."; 87: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 88: } 91: void ReadData 92: ( 93: istream& inStream, //in 94: string& someString //out 95: ) 96: { 97: if (typeid(inStream) == typeid(cin)) 98: cout << "Enter today's secret word from the keyboard: "; 99: getline(inStream, someString); 100: if (typeid(inStream) == typeid(ifstream)) 101: cout << "The secret word has been read from file readwrite.in.\n"; 102: } 105: void WriteData 106: ( 107: ostream& outStream, //inout 108: const string& someString //in 109: ) 110: { 111: if (typeid(outStream) == typeid(cout)) 112: cout << "Here is the secret word: "; 113: outStream << someString << endl; 114: if (typeid(outStream) == typeid(ofstream)) 115: cout << "The secret word has been written to file readwrite.out.\n"; 116: }