0

この小さなプログラムでは、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 をループしてすべての文字を取得するにはどうすればよいですか?

4

3 に答える 3

2

get()ストリームの位置が移動した後。ファイルの終わりに到達し、その位置にある文字にアクセスしようとすると、ストリームは失敗モードにstd::ios_base::failbitなります。つまり、設定されます。失敗モードでは、ストリームは を呼び出すまで何もしませんclear()

通話tellg()はかなり高価であることに注意してください。位置を追跡したい場合は、カウンターを最新の状態に保つ方がはるかに安価です.

于 2013-09-21T18:10:15.100 に答える