9

read.cpp

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    myfile >> id;
    cout << myfile.tellg(); //return 16? but not 7 or 8
    cout << id ;

    return 0;
}

Savingaccount.txt

1800567
Ho Rui Jang
21
女性
マレーシア人
012-4998192
20、Lorong 13、Taman Patani Janam
マラッカ
Sungai Dulong

問題

tellg()返される78、最初の行1800567が7桁であるため、ストリームポインタはこの数値の後、文字列の前に配置する必要があります"Ho Rui Jang"が、をtellg()返します16。なんでそうなの?

4

3 に答える 3

8

同じ問題がありました。ファイルストリームバイナリを読み取ってみてください。

    ifstream myfile("savingaccount.txt",ios::binary);

それは私のために役立ちました

于 2016-08-31T13:41:36.180 に答える
4

これはコンパイラのバグ(おそらくgcc)のようです

次のコードで:-

#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    cout << myfile.tellg()<<endl;
    myfile >> id;
    streamoff pos=myfile.tellg();
    cout <<"pos= "<<pos<<'\n';
    cout <<"id= " << id<<'\n' ;
    return 0;
}

出力は次のとおりです。-

バグ

画像でinpstr.exeVisual studio's clinp.exeg++(gcc version 4.6.1 (tdm-1))

于 2012-09-03T18:10:12.980 に答える
3

コンパイラのバグではありません。 tellg()ファイルの先頭からのオフセットを返すことは保証されていません。tellg()からの戻り値がに渡されたseekg()場合、ファイルポインタがファイル内の対応するポイントに配置されるなど、最小限の保証セットがあります。

実際には、UNIXではtellg()、ファイルの先頭からのオフセットを返します。Windowsでは、ファイルの先頭からのオフセットを返しますが、ファイルがバイナリモードで開かれている場合に限ります。

ただし、唯一の実際の保証は、から返されるさまざまな値がtellg()ファイル内のさまざまな位置に対応することです。

于 2016-08-31T13:53:48.453 に答える