char ch = inFile.get () ; // 讀取一個字元
cout << ch; //輸出字元
ch = inFile.get () ; // 讀取另一個字元
cout << ch; //輸出字元
char ch = inFile.peek () ; //返回下一個字元但是不讀取它
cout << ch; //輸出字元
ch = inFile.get () ; //現在讀取下一個字元
cout << ch; //輸出字元
>>
讀取,但如果資料是非數位字元序列,則應該用 get 或 getline 讀取。// This program demonstrates the peek member function.、 #include <iostream> #include <string> #include <fstream> using namespace std; int main() { // Variables needed to read characters and numbers char ch; int number; // Variables for file handling string fileName; fstream inFile, outFile; // Open the file to be modified cout << "Enter a file name: "; cin >> fileName; inFile.open(fileName.c_str(), ios::in); if (!inFile) { cout << "Cannot open file " << fileName; return 0; } // Open the file to receive the modified copy outFile.open("modified.txt", ios::out); if (!outFile) { cout << "Cannot open the outpur file."; return 0; } // Copy the input file one character at a time except numbers in the input file must have 1 added to them // Peek at the first character ch = inFile.peek(); while (ch != EOF) { //Examine current character if (isdigit(ch)) { // numbers should be read with >> inFile >> number; outFile << number + 1; } else { // just a simple character, read it and copy it ch = inFile.get(); outFile << ch; } // Peek at the next character from input file ch = inFile.peek(); } // Close the files inFile.close(); outFile.close (); return 0; }
程式測試檔案內容:
Amy is 23 years old. Robert is 50 years old. The difference between their ages is 27 years. Amy was born in 1986.
程式輸出結果:
Amy is 24 years old. Robert is 51 years old. The difference between their ages is 28 years. Amy was born in 1987.
>>
來讀取整個數位;如果是字元,則應該通過呼叫 get() 成員函數來讀取)。