1. 程式人生 > >C++的ifstream中使用eof最後一個字元輸出兩次,其實不是eof的鍋!

C++的ifstream中使用eof最後一個字元輸出兩次,其實不是eof的鍋!

寫C++檔案輸入輸出流時遇到的小問題

當我執行以下程式碼時,最後的值會列印兩次:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <fstream>
 4 using namespace std;
 5 
 6 int main(void)
 7 {
 8         int a = 0,b = 1,c = 2,d = 3;
 9         char ch;
10         ofstream FileOpen("Test.txt");
11         FileOpen<<"
HelloWorld!\n"; 12 FileOpen<<a<<b<<c<<d; 13 FileOpen.close(); 14 ifstream Filein("Test.txt"); 15 if(!Filein.eof()) 16 { 17 Filein.get(ch); 18 cout<<ch; 19 } 20 Filein.close(); 21 cout<<endl;
22 system("pause"); 23 return 0; 24 }

問題在於get()方法:get()方法返回當前檔案“內建指標”指向的下一個字元,然後再將“內建指標”向後移動。

也就是說“內建指標”是在執行完get()後才指向下一個字元。

下面來分析一下波:

當“內建指標”指向c時,get()返回d的值給ch,然後“內建指標”向後移動指向d,列印d的值,此時eof()返回false,而迴圈繼續進行;

再次get(),當前“內建指標”指向d,返回的是d後面的值,然而d後面是EOF,讀取失敗,無法賦值給ch,ch依然為d的值,再次列印了一次d的值,get()完後,“內建指標”指向了EOF,eof()返回true,則退出而迴圈。

結束。

原理已經懂了,進行以下的改造即可輸出正確:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <fstream>
 4 using namespace std;
 5 
 6 int main(void)
 7 {
 8         int a = 0,b = 1,c = 2,d = 3;
 9         char ch;
10         ofstream FileOpen(“Test.txt”);
11         FileOpen << "Helloworld!\n";
12         FileOpen << a << b << c << d;
13         FileOpen.close();
14         ifstream Filein("Test.txt");
15         if(Filein.get(ch),!Filein.eof())
16         {
17               cout << ch;
18         }
19         cout << endl;
20         system("pause");
21         return 0;
22 }