What is needed (some method overrides?) in order to read/write binary data to/from std::basic_stringstream? I am trying the following code, but it does not work as I supposed:
std::basic_stringstream<uint64_t> s;
uint64_t a = 9;
s << a;
uint64_t b;
s >> b;
std::cout << b << std::endl;
but I get "0" printed (built with GCC).
The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.
string stream is slow. Quite very slow. If you are writing anything performance critical that acts on large data sets ( say loading assets after a level change during a game ) do not use string streams.
stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated.
If you want to read/write binary data you can't use <<
or >>
you need to use the std::stringstream::read
and std::stringstream::write
functions.
Also you need to use the <char>
specialization because only char
can safely alias other types.
So you could do it this way:
std::stringstream ss;
std::uint64_t n1 = 1234567890;
ss.write((char const*) &n1, sizeof(n1)); // sizeof(n1) gives the number of char needed
std::uint64_t n2;
ss.read((char*) &n2, sizeof(n2));
std::cout << n2 << '\n';
Output:
1234567890
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With