Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::printf

 

std::printf is an STL function to write formatted output to std::cout.

 

std::printf is not typesafe (see example below). For a type-safe alternative, use boost::format instead.

 

 

 

 

 

#include <cstdio>
#include <iostream>
#include <boost/format.hpp>

int main()
{
  //Correct
  std::printf("(x,y) = (%1+5d,%2+5d) \n",-1,2);
  std::cout
    << boost::format("(x,y) = (%1+5d,%2+5d) \n") % -1 % 2;

  //Incorrect
  std::printf("(x,y) = (%1+5d,%2+5d) \n",-1.5,2.5);
  std::cout
    << boost::format("(x,y) = (%1+5d,%2+5d) \n") % -1.5 % 2.5;
}

 

Screen output:

 

(x,y) = ( -1, +2)
(x,y) = ( -1, +2)
(x,y) = ( +0,-1074266112)
(x,y) = ( -1.5, +2.5)

 

 

 

 

 

External links

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict