int get();
istream& get(char& c);
EOF
。EOF
時,第 24?29 行的迴圈終止。
// This program demonstrates the use of the get member // functions of the istream class #include <iostream> #include <string> #include <fstream> using namespace std; int main() { //Variables needed to read file one character at a time string fileName; fstream file; char ch; // character read from the file // Get file name and open file cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) { cout << fileName << " could not be opened .n"; return 0; } // Read file one character at a time and echo to screen ch = file.get (); while (ch != EOF) { cout << ch; ch = file.get(); } // Close file file.close (); return 0; }此程式將顯示任何檔案的內容。由於 get 函數不會跳過白色空格,因此所有字元都將按照檔案中的出現方式顯示。
file.get(ch); while (!file.fail ()) { cout << ch; file.get(ch); }