2

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?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
user855
  • 19,048
  • 38
  • 98
  • 162

2 Answers2

4

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

The fact is that it is exactly what you want.

Jim
  • 3,236
  • 8
  • 33
  • 43
3

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.
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 1
    While this isn't the simplest solution, you get an upvote for providing an iterator; perhaps a `getline_iterator` is actually what the OP needs. A more general solution would probably involve a `partition_iterator` with an input iterator type (`std::istreambuf_iterator` in this case) and accumulator type (`std::string`). – Jon Purdy Aug 30 '11 at 04:18