如何在使用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)
) ;
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- 测试迭代器是否位于列表中的最后一个
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何删除矢量中的重复值,最后一个除外
- 如何在写入文件时擦除最后一个逗号
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- 如何获取 std::filesystem::p ath 中的最后一个目录?