基于 Karma 迭代器的 API(此处)采用...输出迭代器。
您可以为您的阵列创建一个。
问题在于您需要非常确定缓冲区容量永远不会不足:
char buffer[1024];
char* it = buffer;
karma::generate(it, karma::double_ << karma::eol, 3.13);
std::cout.write(buffer, std::distance(buffer, it));
请注意,您不能假设缓冲区是 NUL 终止的。使用生成的大小。
安全使用array_sink
:
在 Boost Iostreams 中有一种更方便、更通用的方法,在面对固定大小的缓冲区时也是安全的:
char buffer[310];
io::stream<io::array_sink> as(buffer);
boost::spirit::ostream_iterator it(as);
这是一个演示特性的现场演示:
Live On Coliru
#include <boost/spirit/include/karma.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
namespace karma = boost::spirit::karma;
namespace io = boost::iostreams;
void test(std::vector<int> const& v)
{
char buffer[310];
io::stream<io::array_sink> as(buffer);
boost::spirit::ostream_iterator it(as);
using namespace karma;
if (generate(it, int_ % ", " << eol, v))
{
std::cout << "Success: ";
std::cout.write(buffer, as.tellp());
} else
std::cout << "Generation failed (insufficient capacity?)\n";
}
int main() {
std::cout << "Should be ok: \n";
std::vector<int> v(100, 1);
test(v);
std::cout << "This will exceed buffer capacity: \n";
std::iota(v.begin(), v.end(), 42);
test(v);
}
哪个打印
Should be ok:
Success: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
This will exceed buffer capacity:
Generation failed (insufficient capacity?)