2013-09-21 42 views
0

在這個小程序中,我只是輸出4個字符到文件,然後檢索它們。正如你可以在輸出中看到的,while循環只讀取4個字符,並且tellp獲取正確的位置,但是一旦外部tellp獲取-1。如何通過ifstream :: get獲取EOF而獲得?

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    ofstream out("E:\\test.txt"); 
    out << "1234"; 
    out.close(); 

    ifstream in("E:\\test.txt"); 

    int i=0; 
    char ch; 
    while(in.get(ch)){ 
     cout << "inside while loop ch="<< ch <<" and its position is " << in.tellg()<< endl; 
     i++; 
    } 
    cout << "outside while loop ch="<< ch <<" and its position is " << in.tellg()<< " and int =" << i <<endl; 
    return 0; 
} 

輸出:

inside while loop ch=1 and its position is 1 
inside while loop ch=2 and its position is 2 
inside while loop ch=3 and its position is 3 
inside while loop ch=4 and its position is 4 
outside while loop ch=4 and its position is -1 and int =4 

,如果我使用:

while(in.get(ch) && in.peek() != EOF){ 
    cout << "inside while loop ch="<< ch <<" and its position is " << in.tellg()<< endl; 
    i++; 
} 

輸出:

inside while loop ch=1 and its position is 1 
inside while loop ch=2 and its position is 2 
inside while loop ch=3 and its position is 3 
outside while loop ch=4 and its position is -1 and int =3 

但這種用法我只得到所有字符除了最後一。以及爲什麼我仍然在這裏-1後,我不能「seekg」了?!!!!!!

我如何循環ifstream :: get並獲取所有字符而沒有得到EOF?

+1

你已經得到所有那些角色。你還想要什麼?? – Saksham

+0

如果你沒有得到'EOF',你怎麼知道你到達了? 如果你討厭'EOF',只需閱讀確切的號碼。來自文件的字符。 – P0W

+0

你正在改變你的時間的休息條件。你期待行爲是一樣的嗎? *爲什麼*? – WhozCraig

回答

2

「我想再次seekg流,我不能」

您可以:

用途:

in.clear(); //Clear flags 
in.seekg(0); //seek to start 

while

1

在每個get()之後,移動流位置。一旦到達文件末尾,並嘗試訪問該位置的字符,則數據流將進入失敗模式,即設置爲std::ios_base::failbit。在故障模式下,只有在致電clear()之前,該流纔會執行任何操作。

請注意,致電tellg()是相當昂貴的。如果你想跟蹤這個頭寸,保持一個櫃檯更新更便宜。

+0

如何「調用tellg()是相當昂貴的。」?我打算通過tellg() –

+0

來跟蹤特定的字符。如果條件在while循環中,我將把它放在: if(ch ==','){ somecevtor.pushback(in.tellg); } –

+0

所以最好做的是「推回(我反擊)」? –

1

爲什麼我仍然在-1這裏後,我不能「seekg」了?

由於while條件評估爲false,並且failbit設置

如果你想這樣做,如果你有字符固定數量的,那麼你應該寧可檢查字符的確切數量比檢查流的有效性。

+0

while循環與文件條件有什麼關係?我不明白 –