4

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)

1
  • Do you just want to initialize the stringstream as in the answer by P0W, or do you want to "use" the buffer in the sense of telling the stringstream to use it as its internal buffer (so, it would, e.g. write new information to it)? I think the latter is not possible with STL, because of reallocations etc. over which you don't have control. Thus STL probably doesn't provide an interface to do it in the first place. Commented Oct 17, 2014 at 6:13

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.