繁体   English   中英

使用 istream_iterator 时如何忽略最后的空行

[英]How to ignore final blank line when using istream_iterator

假设我有一个简单的 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 子句
  • 检查已经存在的 catch 子句中的vec.size()

有没有一种优雅的方式来忽略最后的空行?

改变

    std::copy (
        std::istream_iterator <point <double> > (file), 
        std::istream_iterator <point <double> > (), 
        std::back_inserter (vec)
    ) ;

    std::copy_n (
        std::istream_iterator <point <double> > (file), 
        nPoints, 
        std::back_inserter (vec)
    ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM