1: //input_filename.cpp 2: //Reads the name of an input file from the user. Only an input 3: //file is used, but the same approach applies to output files. 5: #include <iostream> 6: #include <fstream> 7: #include <string> //--Include the "string" header file 8: using namespace std; 10: int main() 11: { 12: cout << "\nThis program asks the user for the name of a file, then " 13: "displays the contents\nof that file on the screen. It continues " 14: "to ask for the names of files and to\ndisplay their contents " 15: "until the user terminates the program by entering an\n" 16: "end-of-file character. Be sure to enter both the file name and " 17: "the extension.\nActually, you can also enter a full pathname to " 18: "a file, or use a logical name\nname as part of the file " 19: "designation, if your system permits such a thing.\n\n"; 21: char ch; 22: string fileName; //--Declare a variable of type "string" 23: ifstream inFile; 25: cout << "Enter name of first file, or " 26: "end-of-file to quit entering filenames:\n"; 27: cin >> fileName; //--Read in the name of the file 28: while (!cin.eof()) 29: { 30: inFile.open(fileName.c_str()); //--Convert C++ string to C-string 31: if (inFile) cout << "\nThe contents of " << fileName << " are:\n"; 32: inFile.get(ch); 33: while (!inFile.eof()) 34: { 35: cout << ch; 36: inFile.get(ch); 37: } 38: inFile.close(); 39: inFile.clear(); 40: cout << endl << endl; 41: cout << "Enter name of next file, or " 42: "end-of-file to quit entering filenames:\n"; 43: cin >> fileName; 44: } 45: //When we come out of the above loop, cin has been "shut down" by 46: //the entry of the end-of-file. If more input from cin is required, 47: //cin must be "cleared", or reset, as follows: 48: cin.clear(); //Check program behavior with this line removed! 49: int i; 50: cout << "\nNow enter an integer: "; 51: cin >> i; cin.ignore(80, '\n'); 52: cout << "The integer entered was " << i << ".\n"; 54: cout << endl; 55: }