#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/assert.hpp>
using namespace boost;
using namespace std;
template<
typename T>
bool num_valid(
const char* str)
{
try
{
lexical_cast<T>(str);
return true;
}
catch(bad_lexical_cast&){
return false;
}
}
class demo_class
{
friend std::ostream&
operator<<(
std::ostream& os,
const demo_class& x)
{
os <<
"demo_class's Name";
return os;
}
};
int main(
int argc,
char **argv)
{
int x = lexical_cast<
int>(
"100");
long y = lexical_cast<
long>(
"2000");
float pai = lexical_cast<
float>(
"3.14159e5");
double e = lexical_cast<
double>(
"2.71828");
cout << x << y << pai << e << endl;
string str = lexical_cast<
string>(
456);;
cout << str << endl;
cout << lexical_cast<
string>(
0.618) << endl;
cout << lexical_cast<
string>(
0x10) << endl;
try
{
cout << lexical_cast<
int>(
"0x100");
cout << lexical_cast<
double>(
"helloworld");
cout << lexical_cast<
bool>(
"false");
cout << lexical_cast<
long>(
"1000L");
}
catch (bad_lexical_cast& e)
{
cout <<
"error:" << e.what()<< endl;
}
assert(num_valid<
double>(
"3.14"));
assert(!num_valid<
int>(
"3.14"));
assert(num_valid<
int>(
"65535"));
cout << lexical_cast<
string>(
"demo_class") << endl;
return (
0);
}
转载请注明原文地址: https://ju.6miu.com/read-1000271.html