Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream and binary data

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).

like image 433
Student4K Avatar asked Nov 05 '17 18:11

Student4K


People also ask

What is a Stringstream?

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.

What should I use for Stringstream?

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”.

Is Stringstream slow C++?

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.

Does Stringstream allocate?

stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated.


1 Answers

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
like image 187
Galik Avatar answered Oct 02 '22 19:10

Galik