4
\$\begingroup\$

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 <iostream>
#include <sstream>
#include <deque>

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

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

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

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

  return get<std::string>(buffer, n);
}


int main()
{
  std::size_t sz;
  while(std::cin >> sz)
    std::cout << readN(sz) << '\n';

  return 0;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.