Implement a readN() from read7() Exercise:


  Using a read7() method that returns 7 characters from a file,
  implement readN(n) which reads n characters.
  
  For example, given a file with the content "Hello world", three
  read7() returns "Hello w", "orld" and then "".


I made a version using std::deque. It seems inefficient to me with all the loops to read/write a string, but I couldn't think of an alternative for this FIFO. Any comments on that part would be especially appreciated.

#include &lt;iostream&gt;
#include &lt;sstream&gt;
#include &lt;deque&gt;

inline auto read7()
{
  static std::istringstream is("1234567890123456789012345678901234567890");
  char res[8]{};
  is.get(res, 8);
  return std::string(res);
}

template &lt;typename T1, typename T2&gt;
auto&amp; operator&lt;&lt;(std::deque&lt;T1&gt;&amp; deq, const T2&amp; seq)
{
  for (const auto&amp; elm : seq)
  {
    deq.push_back(elm);
  }
  return deq;
}

template &lt;typename T1, typename T2&gt;
auto get(std::deque&lt;T2&gt;&amp; deq, std::size_t n)
{
  T1 res;
  while (res.size() != n &amp;&amp; !deq.empty())
  {
    res += deq.front();
    deq.pop_front();
  }
  return res;
}

auto readN(std::size_t n)
{
  static std::deque&lt;char&gt; buffer;
  while (n &gt; buffer.size())
  {
    auto old_sz = buffer.size();
    buffer &lt;&lt; read7();
    if (old_sz == buffer.size())
      break;
  }

  return get&lt;std::string&gt;(buffer, n);
}


int main()
{
  std::size_t sz;
  while(std::cin &gt;&gt; sz)
    std::cout &lt;&lt; readN(sz) &lt;&lt; '\n';

  return 0;
}
Why is read7 declared inline? You should only do this when it's needed as an optimization. (And it's particularly confusing when the function contains a static variable.)

It's not necessary for is to be static. It should really be an argument to read7, so it can work on any istream. (In real code, buffer should also be a parameter to readN, but for this toy problem it's reasonable to have it static.)

Bug: what happens if the input contains null characters?

You could avoid the queue by using a string as the queue. You can simply append the result of each read7 to it until you have enough characters, then remove and return the first n.