使用字符数组作为字符串流缓冲区 [英] Using a character array as a string stream buffer

查看:243
本文介绍了使用字符数组作为字符串流缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个干净的STL方式使用现有的C缓冲区(char *和size_t)作为字符串流。我更喜欢使用STL类作为基础,因为它有内置的保护和错误处理。

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.

注意:我不能使用额外的库(否则我会使用 QTextStream

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

推荐答案

您可以尝试使用 std :: stringbuf :: pubsetbuf 。它调用 setbuf ,但它的实现定义是否会有任何效果。如果是这样,它将用char数组替换基础字符串缓冲区,而不复制所有的内容,如normaly。值得一试,IMO。

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.

使用此代码测试:

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

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

在线演示

这篇关于使用字符数组作为字符串流缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆