boost库学习之 lexical_cast

来源:互联网 发布:java知识分享网 编辑:程序博客网 时间:2024/05/16 23:35
在C中字符串转换为数值,可以使用atoi()、atof()、atol()等,数值转换为字符串可以使用itoa()、sprintf()等,但itoa与编译器有关,并不是标准函数,而sprintf可能会不安全。
使用lexical_cast可以很容易地在数值与字符串之间转换,只需在模板参数中指定转换的目标类型即可。如
  int x = lexical_cast<int>("100");long y = lexical_cast<long>("10000");cout << x << " " << typeid(x).name() << endl;cout << y << " " << typeid(y).name() << endl;string strX = lexical_cast<string>(x);cout << strX << endl;

lexical_cast除了转换数值和字符串也可以只使用1或0转换bool类型.
当lexical_cast无法执行转换操作时会抛出bad_lexical_cast异常,它继承std::bad_cast,所以我们应使用try/catch保护转换代码,如
  try{int x = lexical_cast<int>("100");int y = lexical_cast<int>("test");} catch (bad_lexical_cast& ex) {cout << ex.what() << endl;}

代码输出:bad lexical cast: source type value not be interpreted as target
如果被转换的参数是NULL, 如 int x = lexical_cast<int>(NULL); 那么x 为0
我们也可根据该异常来编写验证数字字符串的合法性
template<typename T>bool isValidNumStr(const char* str) {if (str == nullptr) {return false;}try {lexical_cast<T>(str);return true;}catch (bad_lexical_cast& ex) {return false;}}




0 0