在這個小程序中,我只是輸出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?
你已經得到所有那些角色。你還想要什麼?? – Saksham
如果你沒有得到'EOF',你怎麼知道你到達了? 如果你討厭'EOF',只需閱讀確切的號碼。來自文件的字符。 – P0W
你正在改變你的時間的休息條件。你期待行爲是一樣的嗎? *爲什麼*? – WhozCraig