Using a character array as a string stream buffer

老子叫甜甜 提交于 2019-12-20 02:54:06

问题


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:


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.



来源:https://stackoverflow.com/questions/26418693/using-a-character-array-as-a-string-stream-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!