Chiune Sugihara
Chiune Sugihara

Reputation: 1229

Reading in a std::array from an input stream

I would like to accomplish the following (code won't compile as written because >> isn't overloaded for std::array):

constexpr array<char, 2> MAGIC_BYTES { 40, 23 };

void VerifyMagicHeader(istream& stream)
{
    //Read in the bytes that should be the magic bytes
    array<char, 2> buffer;
    stream >> buffer //This is the line that won't compile;

    if (buffer != MAGIC_BYTES)
    {/*throw exception here...*/}
}

I know that I can read in a char[2] instead of an std::array<char, 2> and get this to work but it wouldn't be as elegant. This seems like an operator that would be really helpful for std::array to have so I am wondering if there is a reason why it isn't implemented or if I will need to implement it myself.

Upvotes: 1

Views: 1721

Answers (2)

Elvis Dukaj
Elvis Dukaj

Reputation: 7368

This method is my favorite if you don't need performance (and for 2 bytes you don't need it) and is based on standard algorithms:

std::copy_n(std::istream_iterator<char>{stream}, 2, begin(MAGIC_BYTES))

Now MAGIC_BYTES can be a vector or a string or some other container with random access!

Upvotes: 4

Alan Birtles
Alan Birtles

Reputation: 36389

It isn't implemented as standard as there is no single way for the array to be read/written some examples:

  1. as a binary stream of characters
  2. as a comma separated list (what if one of your characters is a comma?)
  3. as a space separated list (what if one of your characters is a space?)

Then when you add in that array is a templated class it gets even more complicated. How do you write an array of arrays?

None of the STL containers define stream operators for the same reasons.

Upvotes: 4

Related Questions