The boost::lexical_cast<> utility library

The boost::lexical_cast<> is a small convenience library which allows easy conversion between objects and their string representations. The typical use of this library is for conversion of numerical values encoded as character strings to their binary form. The simplest example of usage is:

const char * inputstringvol = "0.05";
const double vol = boost::lexical_cast<double>(inputstringvol);

The key features of this library are:

  • Clear and convenient syntax
  • Type-safety
  • Conversion of user-defined types
  • Exceptions are thrown if problems in the conversion are encountered

Here is a minimal program illustrating the key features:

#include <iostream>
#include <boost/lexical_cast.hpp>

void printTimesTwo(double x)
{
  std::cout<<(2*x)
        <<std::endl;
}

int main(int argc, char **argv)
{
  // Convert parameter 1 of the program and print double its value
  printTimesTwo(boost::lexical_cast<double>(argv[1]));

  // The following line would *not* compile because of the type
  // checking
  // std::string s=boost::lexical_cast<double>(argv[1]);

  // Demonstrate the exception mechanism
  try
  {
    // Try to conver parameter 0 which is program name
    printTimesTwo(boost::lexical_cast<double>(argv[0]));
  }
  catch (const boost::bad_lexical_cast &bc)
  {
    std::cout<<"Caught an exception as expected: "
          <<std::endl
          <<"    "<<bc.what()
          <<std::endl;
  }
}

The usage of this library is recommended in following cases:

  • Whenever you would have used the C-library functions ato{i,f,d}
  • When using the C++ standard library routines would have made for longer and/or more obscure code. For example:
#include <iostream>
#include <sstream>
#include <boost/lexical_cast.hpp>

double twice(const char * i)
{
  return 2*boost::lexical_cast<double>(i);
}

double twice_old(const char * i)
{
  std::stringstream s(i);
  double temp;
  s>>temp;
  return 2*temp;
}

int main(void)
{
  std::cout<<twice("4.0")<<std::endl
       <<twice_old("5.0")<<std::endl;

}
  • When parsing input parameters to a program or input data files

Within the QF field a typical usage would be to convert a character string passed from a cell within a spreadsheet into a numerical value.