C ++流到字符数组? [英] c++ streaming into char array?

查看:56
本文介绍了C ++流到字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im当前正在使用ac库的c ++应用程序上工作,该程序需要从我端
实现的回调,例如,该回调定义为:

  int onWrite(char *什么,char *缓冲区,size_t大小,off_t偏移量); 

我有std :: set,需要格式化并将其写入缓冲区,并注意大小和offset其中size是缓冲区的大小,offset已经处理了多少字节



有没有一种C ++方式可以像流一样流入缓冲区?
我想到了这样的东西:

  SomeSTLStandardStream stream(buffer,size); 
stream.ignore(offset); //删除前n个偏移量字节
for(it = dataset.begin(); it!= dataset.end()&& stream.buffer_avail()> 0; it ++)
流<< *它<< |; //格式化csv,例如

我的核心问题是:是否有标准的c ++方式

如果只生病,必须实现自己的格式



我也看过stringstream,但是它似乎不完全符合我的需要,因为它使用了自己的写缓冲区而不是我的
,而且我也不知道已经写了多少个字节,所以....



thx

解决方案

您可以分配内存并使用 std :: stringstream将其包装在字符串流中: :pubsetbuf

  int main()
{
char buf [1024];

std :: stringstream流;

stream.rdbuf()-> pubsetbuf(buf,sizeof(buf));

流<< 你好<< 世界<< std :: endl;

std :: string str;
std :: getline(stream,str);
std :: cout<< str<< std :: endl;

// ...
}

阅读 std :: stringstream ,< a href = http://en.cppreference.com/w/cpp/io/basic_streambuf rel = nofollow> std :: basic_streambuf std :: basic_stringbuf


im currently working on a c++ application which is using a c library which needs a callback implemented from my side for example the callback is defined as this:

int onWrite(char *what, char *buffer, size_t size, off_t offset);

i have std::set which needs to be formated and written into buffer and take care of size and offset where size is buffer's size and offset how many bytes have already been processed

is there a c++ way where i can stream-like into buffer? i think about something like this:

SomeSTLStandardStream stream(buffer,size);
stream.ignore(offset);  // to drop the first n offset bytes
for(it=dataset.begin();it!=dataset.end() && stream.buffer_avail()>0;it++)
    stream << *it << "|"; // format csv like for example

the core question i have is: is there a standard c++ way to grab just a slice of formated/streamed data and write into given buffer?

if not ill have to implement my own

i also had a look at stringstream but it doesnt seem to fit exactly to my needs cause its using its own write buffer instead of mine and i dont know how many bytes have already been written to it too and such....

thx

解决方案

You can allocate memory and wrap it in a string stream by using std::stringstream::pubsetbuf:

 int main()
 {
    char buf[1024];

    std::stringstream stream;

    stream.rdbuf()->pubsetbuf(buf, sizeof(buf));

    stream<< "Hello " << "World " << std::endl;

    std::string str;
    std::getline(stream, str);
    std::cout << str << std::endl;

    //...
}

Read std::stringstream, std::basic_streambuf and std::basic_stringbuf.

这篇关于C ++流到字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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