There’s an interesting conversion mechanism called lexical_cast provided in the boost conversion library. The primary purpose of lexical_conversion is to convert primitive data types to string and vice versa.
Standard C++ Library provides stringstream class to do the conversion and we can have great control on the precision and format of conversion but for the simple conversion stringstream library is not good enough. we need to declare additional variables of string stream kind and to use obscure syntax to do the simple conversion. On the other hand lexical_cast is simple to use and readable with it’s syntax.
One of the major use of lexical_cast is with the configuration files of your application which contains the numerical data in string format. while reading, it should be converted to integral or floating type and when we write it back, we have to convert it back to string format.
For the control over precision and formatting requirements, it’s better to use stringstream class and for the conversion between Numerical type, boost offers boost::numeric_cast
Sample Snippet;
#include <boost/lexical_cast.hpp>
#include <iostream>
//char* table[] = { “10″,”20″,”20″,”40″,”bad” };
int table[] = { 10,20,20,40,0×20 };
int main(int argc, char* argv[])
{
for( int i = 0; i< 5; ++i)
{
try
{
// Taking output to a variable is only to verify in the debug mode output
std::string s = boost::lexical_cast<std::string>( table[i] ) ;
std::cout << s <<std::endl;
/*short s = boost::lexical_cast<short>( table[i] ) ;
std::cout << s <<std::endl; */
}
catch( boost::bad_lexical_cast& lex )
{
std::cout << lex.what();
}
}
return 0;
}
Boost Library contains good description and sample code for each items. Please check boost::lexical_cast for more information