Noone AtAll
Noone AtAll

Reputation: 385

How can I create string out of specific amount of bytes from istream?

I need to create a std::string with first N bytes of istream... How do I do that?

std::istream istm;

std::string  str;
istm >> str;              //will read tons of stuff until finds whitespace

std::string  str(N, ' ');
istm.read(str.data(), N); //can't write into buffer inside string, cause data() returns const char*

std::unique_ptr<char[N+1]> buf;
istm.read(buf.get(), N);
std::string str(buf.get());                //should work, but why extra buffer?

so... how do I do that a good way?

Upvotes: 0

Views: 58

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

There's a non-const data() since C++17.

Before then, you can pass &str[0] instead, which gives you the same thing.

Note that this was technically unsafe until C++11, as C++98/03 did not explicitly guarantee contiguous storage for string data (though this was generally the case in practice for a number of reasons).

Upvotes: 1

Related Questions