C++ファイル読み出し末尾eof()
皆さんはc++のファイル読み書きストリームを使ったことがあると思いますが、ファイルを読み書きする際にeof()を利用してファイルの末尾に達したかどうかを判断します.以下のようにします.
最も簡単な解決策は、読み取り後に読み取りに成功したか否かを判断し、
ifstream inf("test.txt");
if ( !inf.is_open() )
{
cout <>shape;
inf >>answer;
inf >>right_or_wrong;
CPolygon *p;
if ( shape == " " ) p = (CPolygon *)(new CSquare(shape,answer,right_or_wrong));
else if( shape == " " ) p = (CPolygon *)(new CRectangle(shape,answer,right_or_wrong));
else if ( shape == " " ) p = (CPolygon *)(new CCrescentShaped(shape,answer,right_or_wrong)) ;
else if( shape == " " ) p = (CPolygon *)(new CTriangle(shape,answer,right_or_wrong));
else if( shape == " " ) p = (CPolygon *)(new CTrapezoidal(shape,answer,right_or_wrong));
else if( shape == " " ) p = (CPolygon *)(new CRound(shape,answer,right_or_wrong));
else p = (CPolygon *)(new CStar(shape,answer,right_or_wrong));
m_fromfile.push_back(p);
}
}
inf.close();
この時、私は驚いたことに、読み取り時にファイルの最後のデータが繰り返し読み込まれたことに気づき、非常に理解できませんでした.ネットで検索したところ、元々はファイルの読み取りに成功したかどうかは関係なく、ファイルの最後のデータを読んだときに、読み取りに行き、実際には読み取りに失敗したが、shapeなどに保存されていたデータは変化しなかったため、最後のデータを繰り返し出力するオブジェクトが構築された.最も簡単な解決策は、読み取り後に読み取りに成功したか否かを判断し、
inf >>right_or_wrong;
CPolygon *p;
の間に判断文を付けて、読み取りに成功したかどうかを判断します.失敗するとループから飛び出し、逆に実行を続行します. if(!inf)
break;
これでプログラムは正常に実行されます.