この小さなプログラムでは、4 文字をファイルに出力してから取得しています。出力でわかるように、while ループは 4 文字しか読み取らず、tellp は正しい位置を取得しますが、tellp の外側では -1 になります。
#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 を取得しているのですか?
EOF を取得せずに ifstream::get をループしてすべての文字を取得するにはどうすればよいですか?