How does one generate from boost karma into C++ array? -
i see how karma can used generate container manages memory, std::string. case buffer (char[n]) has been pre-allocated?
{ using namespace boost::spirit::karma; { std::string buffer; generate(std::inserter(buffer, buffer.begin()), double_, 3.13); std::cout << ':' << buffer << ':' << std::endl; } { ////////////////////////////////////////////////////////////////////// // how make following work? there builtin output // iterator works? #if defined(majic) char buffer[1024]; generate(buffer, double_, 3.13); std::cout << ':' << buffer << ':' << std::endl; #endif } }
i find way parse double address of existing buffer. ok assume buffer large enough case. maybe underlying question - there output iterator adapter or in karma native arrays used?
the karma iterator-based api (here) takes... output iterators.
you can create 1 array.
problem need sure buffer capacity never being insufficient:
char buffer[1024]; char* = buffer; karma::generate(it, karma::double_ << karma::eol, 3.13); std::cout.write(buffer, std::distance(buffer, it));
note how cannot assume buffer nul-terminated. use generated size.
safe using array_sink
:
there's more convenient, more general approach in boost iostreams safe in face of fixed-size buffers too:
char buffer[310]; io::stream<io::array_sink> as(buffer); boost::spirit::ostream_iterator it(as);
here's live demo demonstrates characteristics:
#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 ok: \n"; std::vector<int> v(100, 1); test(v); std::cout << "this exceed buffer capacity: \n"; std::iota(v.begin(), v.end(), 42); test(v); }
which prints
should 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 exceed buffer capacity: generation failed (insufficient capacity?)
Comments
Post a Comment