次のような 2D 点の単純なテキスト ファイルがあるとします。
10
0.000 0.010
0.000 0.260
0.000 0.510
0.000 0.760
0.000 1.010
0.000 1.260
0.000 1.510
0.000 1.760
0.000 2.010
0.000 2.260
// Blank line here
IO に単純な構造体を使用します。
template <typename T>
struct point
{
point (T x = 0, T y = 0) : x (x), y (y) {}
T x ;
T y ;
friend std::istream& operator>> (std::istream &is, point &p) {
is >> p.x >> p.y ;
return is ;
}
};
私の元のコードは次のとおりです。
int main (void)
{
std::string strFile = "Points.txt" ;
std::ifstream file ;
file.exceptions (std::ios::failbit | std::ios::badbit) ;
std::vector <point <double> > vec ;
try {
file.open (strFile) ;
int nPoints = 0 ;
file >> nPoints ;
for (int n = 0; n < nPoints; ++n) {
point <double> p ;
file >> p ;
vec.push_back (p) ;
}
}
catch (std::ios_base::failure &e) {
std::cerr << e.what () << "\n" ;
return 1 ;
}
return 0 ;
}
これは問題なく動作しますが、生のループがないという精神で、for ループを取り除きたいと思います。
ここに私の新しいコードがあります:
int main (void)
{
std::string strFile = "Points.txt" ;
std::ifstream file ;
file.exceptions (std::ios::failbit | std::ios::badbit) ;
std::vector <point <double> > vec ;
try {
file.open (strFile) ;
int nPoints = 0 ;
file >> nPoints ;
std::copy (
std::istream_iterator <point <double> > (file),
std::istream_iterator <point <double> > (),
std::back_inserter (vec)
) ;
}
catch (std::ios_base::failure &e) {
std::cerr << e.what () << "\n" ;
return 1 ;
}
return 0 ;
}
すべてが正常にコピーされますが、残念ながら、最後の空白行を読み取ると、フェイル ビットが設定されます。
これを修正する唯一の方法は、ちょっと醜いです。私はできた:
point::operator>>()
関数に try-catch 句を入れるvec.size()
すでに存在する catch 句をチェックインします。
最後の空白行を無視するエレガントな方法はありますか?