C++ boost::format














































C++ boost::format



Description: As in the c language printf("%3d",&a) is used for the format in which we want to print for this only the alternative is boost::format which is used here for the higher order numbers . boost::format is a class in which there is a string containing special characters to control formatting which is passed to the constructor of boost::function class.The data that replaces these special characters in the output is linked via the operator%.
The format object is constructed from a format-string and is then given arguments through repeated calls to operator%.Each of these arguments are then converted to strings ,who are in turn combined into one string ,according to format-string

Syntax: General syntax of format string is:
                  boost::format(format string)%arg1,%arg2,....%argN

Directives in format string:
 1.printf format string : In this %spec is used as the general syntax .the printf format supported boost.format follows the                                              Unix98 open group printf precise syntax rather than the standard c language 
    The specification spec has the form :
                 [ N$ ] [ flags ] [ width ] [.precision] [argument-type] conversion-specifier.   (any of the field any be optional)
                  >   [ N$ ] : it is  known as positional format specification .if it is not present then the argument will be taken one                                      by one 
                  >   [flag] : flag    is sequence of any of these:

    > [width]: it specifies the minimal width of the string resulting from the conversion.
    >[.precision]: it sets the stream precision .when output is the float type number,it sets the maximum number of                                       digits after decimal point in fixed or scientific mood and when in default mood(eg: %g)
    >[argument-type]: in printf family it is used to process the argument but in boost::format it is used with %                                               operator  which allows the template to carry the argument type.Argument type hh,h,l,ll,j,z and L are                                       recognized as the Microsoft extensions w,I,i32,i64.
    >conversion-specifier: 

 2.%|spec| : where spec is same as printf format specification as i explained in first point.
                   the pip delimited syntax is introduced  to improve the readability of the format string but primarily to                                     make the type conversion optional in spec 
   3.%N%:  this is the simple positional notation request the formatting of the nth argument without any formatting                                   option

Manipulators : Here the arguments can be modified using ios flags through group function in the group                                                         function(group()) the last argument in the function is the actual numbers for ios manipulators go to the                                    link https://doc.bccnsoft.com/docs/cppreference_en/io_flags.html

Advantages: 
1.safe : type-safe,and throws an exception ,for example the specification of too-many or too few  arguments
2.extensible : work for any type that can be streamed
3.convenient: standard posix and similar format string

program:

#include <boost/format.hpp>
#include <iostream>
#include <iomanip>
#include <boost/cast.hpp>
#include <cassert>
//writing two customised namespace for easy readability
using namespace std;
namespace MyNS_ForOutput {
using std::cout;
using std::cerr;
using std::string;
using std::endl;
using std::flush;
using boost::format;
using boost::io::group;
using boost::io::str;
}

namespace MyNS_Manips {
using std::setfill;
using std::setw;
using std::hex ;
using std::dec ;
}
int main()
{
using namespace MyNS_ForOutput;// these are two customised namespace names
using namespace MyNS_Manips;
cout<<"these simple use of boost::format:"<<endl;
/*
as I explained in the derivatives of format string %spec so some of the examples are explained below
as %$1 %$2 it means that it should take first and second argument respectively .
after that it has + sign which will print the number as it is and 5 width as we notice output it will show
that it has that 5 width space for -23 and same for 35 . and though it is not decimal point but still the
conversion specifier is d because it covers almost all types so when we are not sure we gave d
and if when it comes to alignment then by default it right side alignment and others we can see in output
*/

cout<<"normal use \n";
cout <<boost::format("(x,y) = (%1$+5d,%2$-5d ,%2$=5d) \n") % -23 % 35; // positional syntax

/* Note: conversion specifier does not strictly imposed on the arguments but it is used for ios flag
as u can see for string it is s but if u change it d also it does not effect our output
as the clear difference is there in next line where 18 is shown as x ,o , s
*/

cout<<"\n use of different conversion specifier\n";
cout << boost::format("writing %s, x=%d : %d-th step \n") % "toto" % 40.23 % 50;
cout <<boost::format("_%1$4d_ is : _%1$#4x_ in hexadecimal, _%1$#4o_ in octal, and _%1 in string \n") % 18;

// it is the example of %N% where spec format is same
cout<<"\n use of %N% \n";
cout << boost::format("%1%.%2%.%3%") % 12 % 5 % 2014 << '\n';

// it is the example of %|spec| and here also spec has same format as first one
cout<<"\n use of %|spec| \n";
cout << boost::format("%|1$1| %|2$20|") % "Hello" % 3 << std::endl;


cout<<"here below it is shown that same output can be there with different format writing"<<endl;
cout <<boost::format("(x,y) = (%+5d,%+5d) \n") % -23 % 35; //non positional syntax
cout << boost::format("(x,y) = (%|+5|,%|+5|) \n") % -23 % 35;
cout << boost::format("(x,y) = (%|1$+5|,%|2$+5|) \n") % -23 % 35;

/* know here it is shown that boost::format can be used with ios flag manipulators
as the internal format stream can be changed by manipulators only using the group function
*/

cout<<"\n use of manipulators \n";
cout <<boost::format("%2% %1% %2%\n") % 1 % group(setfill('X'), hex, setw(4), 16+3) ;

/* know below we can see that assertion is used as we know assertion is a sanity check that you
can turn on and off when you have finished testing
so by putting the format under one string and checking it
*/

cout<<"\n use of assertion \n";
std::string s;
s= str( format(
" %d %d ") % 11 % 22 );
assert( s ==
" 11 22 ");
cout << format("%%##%#x ") % 20 << endl;

cout<<"added features in printf"<<endl<<endl;
cout<<"same arguments can be used number of times \n";
cout << format("%1% %2% %3% %2% %1% \n") % "o" % "oo" % "O";

// Tabulations : "%|Nt|" => tabulation of N spaces.
// "%|NTf|" => tabulation of N times the character <f>.
/* we want to print multiple values at a time so we can use the simple vector concpet where
parameterized constructor is used as container of size 1 is created
*/

cout<<"\n use of vector\n";
vector<string> names(1, "sunita"),
surname(
1,"konada"),
tel(
1, "6745218890");
// apart from the container size we can manually add the values using push_back function
names.push_back(
"chaitanya");
surname.push_back(
"gunda sai");
tel.push_back(
"6777290123");

for( int i=0; i<names.size(); ++i) // as we can see boost::format is used with vector
cout << format("%1%, %2%, %|20t|%3%\n") % names[i] % surname[i] % tel[i]; // and with vector it will use 3rd syntax thats why additionally
cout << "\n"; //width is used



// truncation s of strings as s takes the string and trunc it to two characters and for c
// it will take the single character from the string user
cout<<"\n truncation of string \n";
cout << format("%|.2s| %|8c|.\n") % "root" % "user";




// here we can see the nesting of the format string and the manipulators
cout<<"\n nested output \n";
cout << format("%2$014x [%1%] %2$05s\n") % (format("%05s / %s") % -18 % 7)
% group(showbase,
-100);




}


output:
these simple use of boost::format:
normal use
(x,y) = ( -23,35 , 35 )

use of different conversion specifier
writing toto, x=40.23 : 50-th step
_ 18_ is : _0x12_ in hexadecimal, _ 022_ in octal, and _18_ in string

use of %N%
12.5.2014

use of %|spec|
Hello 3
here below it is shown that same output can be there with different format writing
(x,y) = ( -23, +35)
(x,y) = ( -23, +35)
(x,y) = ( -23, +35)

use of manipulators
XX13 1 XX13

use of assertion
%##0x14
added features in printf

same arguments can be used number of times
o oo O oo o

use of vector
sunita, konada, 6745218890
chaitanya, gunda sai, 6777290123


truncation of string
ro u.

nested output 
0x0000ffffff9c [-0018 / 7] -0100

Note: As we seen there non-positional format(%d) and positional format (%$4) and they should not be used together 
        // unsupported printf directives %n and asterisk-fields are purely ignored.
// do *NOT* provide an argument for them, it is an error.
cout << format("|%5d| %n") % 7 << endl;
// prints "| 7| "
cout << format("|%*.*d|") % 7 << endl;
// prints "|7|"



More Articles of Konada Sunita:

Name Views Likes
C++ boost::accumulator::p_square_cumulative_distribution 672 1
C++ boost::Numeric Conversion::converter<> 864 10
C++ boost::ref 1227 9
C++ boost::accumulator::count 930 2
C++ boost::function::function_base 557 10
C++ boost::accumulator::weighted_mean 889 1
C++ boost::accumulator::non_coherent_weighted_tail_mean 563 1
C++ boost::accumulator::rolling_count rolling_sum rolling_mean rolling_moment 727 2
C++ boost::lockfree::spsc_queue 2202 10
C++ boost::coroutine:: passing data 640 1
C++ boost::accumulator::weighted_tail_quantile 619 1
C++ boost::TokenizerClass 83 2
C++ boost::accumulator::weighted_variance 559 1
C++ boost::accumulator::rolling mean 2595 2
C++ boost::accumulator::median 1417 1
C++ boost::accumulator::extended_p_square_quantile 837 1
C++ boost::accumulator::extended_p_square 648 1
C++ boost::function::functionN 829 10
C++ boost::accumulator::weighted_density 505 1
C++ boost::accumulator::covariance density 780 3
C++ boost::accumulator::weighted_skewness 503 1
C++ boost::format::formatter 654 10
C++ boost::accumulator::skewness 911 1
C++ boost::accumulator::max 700 3
C++ boost::accumulator::variance 992 1
C++ boost::accumulator::min 592 2
C++ boost::accumulator::density 951 1
C++ boost::token_iterator 885 10
c++ program to print root to leaf paths without using recursion 705 10
C++ boost::accumulator::rolling variance 1476 4
C++ boost::accumulator::weighted_sum 544 1
C++ boost::accumulator::weighted_extended_p_square_quantile 605 2
C++ boost::accumulator::sum_kahan 1117 2
C++ boost::accumulator::weighted_moment 469 1
C++ boost::accumulator::error_of 658 2
C++ boost::accumulator::tail 845 2
C++ boost::format 4139 10
C++ boost::accumulator::weighted_p_square_cumulative_distribution 522 1
C++ boost::accumulator::coherent_tail_mean 471 1
C++ boost::accumulator::rolling count 1153 2
C++ boost::accumulator::moment 703 2
C++ boost::lockfree::stack 1207 8
C++ boost::accumulator::sum 821 2
C++ boost::function::bad_function_call() 1096 10
C++ boost::accumulators::Mean Moment Count 1370 2
C++ boost::accumulator::mean 1617 2
C++ boost::accumulator::non_coherent_tail_mean 501 1
C++ boost::accumulator::weighted_extended_p_square 521 1
C++ boost::accumulator::weighted_kurtosis 522 1
C++ boost::accumulator::covariance density error_of_mean 587 9
C++ boost::accumulator::rolling sum 834 2
C++ boost::lockfree::queue 3084 9
C++ boost::accumulator::weighted_p_square_quantile 852 1
C++ boost::accumulator::p_square_quantile 840 1
C++ boost::accumulator::tail_quantile 1201 1
C++ boost::accumulator::rolling moment 598 2
C++ boost::accumulator::min max 1230 3
C++ boost::accumulator::kurtosis 1209 1
C++ boost::coroutine::Pushtype and pulltype 1564 1
C++ boost::accumulator::tail_variate 491 2
C++ boost::accumulator::weighted_covariance 519 2
C++ boost::format::Exception 2202 10
C++ boost::function 3035 10
C++ boost::NumericConversion::bounds<> 677 10
C++ boost::NumericConversion::UDT 853 10

Comments