开发者

Using an istream_iterator to read strings in multiple lines

I want to read the following input:

Foo 1 2 4 
Bar 3 4 5

as two separate "string" objects.

Is it possible to accomplish this using istream_iterator?

Where can I find a good documentation on all these iterators?开发者_Go百科


You will want to use getline(): http://www.cplusplus.com/reference/iostream/istream/getline/

The fact is that it is exactly what you want.


I assume that you don't need to use std::istream_iterator specifically, since it won't do what you want. Would a different iterator work for you?

#include <iterator>
#include <iostream>

class getline_iterator
  : public std::iterator<std::input_iterator_tag, std::string>
{
private:
  std::istream* is;
  std::string line;
  void fetchline() {
    if (is && !std::getline(*is, line)) is = 0;
  }

public:
  getline_iterator(std::istream& is) : is(&is) {
    fetchline();
  }
  getline_iterator() : is(0) { }
  std::string operator*() {
    return line;
  }
  getline_iterator& operator++() {
    fetchline();
    return *this;
  }
  bool operator==(const getline_iterator& rhs) const {
    return (!rhs.is) == (!is);
  }
  bool operator!=(const getline_iterator& rhs) const {
    return !(rhs == *this);
  }
};

int main()
{
  getline_iterator begin(std::cin);
  getline_iterator end;
  std::copy(begin, end, std::ostream_iterator<std::string>(std::cout, "\n"));
}


EDIT: I missed the 2nd question: "Where can I find a good documentation on all these iterators?" I personally find http://cplusplus.com/reference/std/iterator/ useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜