Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a character array as a string stream buffer

I'm looking for a clean STL way to use an existing C buffer (char* and size_t) as a string stream. I would prefer to use STL classes as a basis because it has built-in safeguards and error handling.

note: I cannot use additional libraries (otherwise I would use QTextStream)

like image 406
Gravis Avatar asked Sep 20 '25 09:09

Gravis


1 Answers

You can try with std::stringbuf::pubsetbuf. It calls setbuf, but it's implementation defined whether that will have any effect. If it does, it'll replace the underlying string buffer with the char array, without copying all the contents like it normaly does. Worth a try, IMO.

Test it with this code:

std::istringstream strm;
char arr[] = "1234567890";

strm.rdbuf()->pubsetbuf(arr, sizeof(arr));
int i;
strm >> i;
std::cout << i;

Live demo.

like image 158
jrok Avatar answered Sep 23 '25 00:09

jrok