Converting data from strings to numeric types is a boring and error prone task, luckly we can use lexical_cast, as showed in this example:
#include <iostream>
#include <string>
#include "boost/lexical_cast.hpp"
using std::string;
using std::cout;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
void lexical()
{
// string to int
string s("42");
int i = lexical_cast<int>(s);
cout << "fortytwo as string " << s << " and as int " << i << endl;
// float to string
float f = 3.14151;
s = lexical_cast<std::string>(f);
cout << "PI as float " << f << " and as string " << s << endl;
// literal to double
double d = lexical_cast<double>("2.52");
cout << "A double from a string " << d << endl;
// Failed conversion
s = "Not an int";
try
{
i = lexical_cast<int>(s);
}
catch(bad_lexical_cast& blc)
{
cout << "Exception " << blc.what() << endl;
}
}
It is easy to think about a template function that would convert to a string its input:
#include <iostream>
#include <string>
#include "boost/lexical_cast.hpp"
using std::string;
using std::cout;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
namespace
{
template <typename T>
string toString(const T& arg)
{
try {
return lexical_cast<string>(arg);
}
catch(boost::bad_lexical_cast& e) {
return "";
}
}
}
void lexical2()
{
string s = toString(42);
cout << "int to string " << s << endl;
s = toString(3.14151);
cout << "float to string " << s << endl;
}
No comments:
Post a Comment