C++: Input Loop

Bjarne-stroustrup
 


Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.

The following functions send the words resp. lines to a generic output iterator.

#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
 
// word by word
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
  std::string word;
  while (is >> word)
  {
    // send the word to the output iterator
    *dest = word;
  }
}
 
// line by line:
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
  std::string line;
  while (std::getline(is, line))
  {
    // store the line to the output iterator
    *dest = line;
  }
}
 
int main()
{
  // 1) sending words from std. in std. out (end with Return)
  read_words(std::cin, 
             std::ostream_iterator<std::string>(std::cout, " "));
 
  // 2) appending lines from std. to vector (end with Ctrl+Z)
  std::vector<std::string> v;
  read_lines(std::cin, std::back_inserter(v));
 
  return 0;
}

An alternate way to read words or lines is to use istream iterators:

template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<std::string> InIt;
    std::copy(InIt(is), InIt(),
              dest);
}
 
namespace detail 
{
    struct ReadableLine : public std::string 
    { 
        friend std::istream & operator>>(std::istream & is, ReadableLine & line)
        {   
            return std::getline(is, line);
        }
    };
}
 
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<detail::ReadableLine> InIt;
    std::copy(InIt(is), InIt(),
              dest);
}

SOURCE

Content is available under GNU Free Documentation License 1.2