C++标准库中字符串转数值使用函数atoi(),数值转字符串使用printf系列函数。
boost中使用转换函数操作符lexical_cast<>进行转换,实际上是模板函数。自定义类型,要进行转换必须支持输入输出操作符<< >>。
#include <iostream> #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; int main() try { int x = lexical_cast<int>("100"); long y = lexical_cast<long>("2000L"); float pai = lexical_cast<float>("3.14159e5"); double e = lexical_cast<double>("2.71828"); cout << x <<endl<< y<<endl << endl<<pai <<endl<< e <<endl; string str = lexical_cast<string>(456); cout << str << endl; } catch(bad_lexical_cast& e) { cout <<"error:" << e.what() <<endl; }
2.格式转换format,其实输入输出分三部分,一个类型转换,一个格式转换,一个输出。format用于格式转换接受用于转换的格式字符串产生format对象,使用重载操作符%进行格式转换。
#include <iostream> #include <boost/format.hpp> using namespace std; using namespace boost; int main() { format fmt("%05d %-8.3f %10s %05X "); cout << fmt %62 %2.236%"123456789"%48; return 0; }