我写的是LineInputIterator(写成一个练习,但也许有一天会有用):#ifndef UB_LINEINPUT_ITERATOR_H#define UB_LINEINPUT_ITERATOR_H#include #include #include
#include namespace ub {template class LineInputIterator :
public std::iterator<:input_iterator_tag>{public:
typedef typename StringT::value_type char_type;
typedef typename StringT::traits_type traits_type;
typedef std::basic_istream istream_type;
LineInputIterator(): is(0) {}
LineInputIterator(istream_type& is): is(&is) {}
const StringT& operator*() const { return value; }
const StringT* operator->() const { return &value; }
LineInputIterator& operator++()
{
assert(is != NULL);
if (is && !getline(*is, value)) {
is = NULL;
}
return *this;
}
LineInputIterator operator++(int)
{
LineInputIterator prev(*this);
++*this;
return prev;
}
bool operator!=(const LineInputIterator& other) const
{
return is != other.is;
}
bool operator==(const LineInputIterator& other) const
{
return !(*this != other);
}private:
istream_type* is;
StringT value;};} // end ub#endif
因此,您的循环可以替换为一个算法(C+中的另一个推荐做法):for_each(LineInputIterator<>(cin), LineInputIterator<>(), do_stuff);
也许一个常见的任务是将每一行存储在一个容器中:vector lines((LineInputIterator<>(stream)), LineInputIterator<>());