当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Boost.Lexical_Cast用法及代码示例


库“boost/lexical_cast.hpp”中定义的Boost.LexicalCast提供了强制转换运算符boost::lexical_cast,可以将数字从字符串转换为数字类型,如int或double,反之亦然。

boost::lexical_cast是std::stoi(,std::stod(和std::to_string()等函数的替代方法,它们已添加到C++ 11中的标准库中。现在让我们在程序中查看此函数的实现。例子:

Conversion
integer -> string
string- > integer
integer -> char
float- > string

关联的异常:如果转换失败,则引发从bad_cast派生的bad_lexical_cast类型的异常。引发异常是因为浮点数52.50和字符串“GeeksforGeeks”无法转换为int类型的数字。


// CPP program to illustrate 
// Boost.Lexical_Cast in C++ 
#include "boost/lexical_cast.hpp" 
#include <bits/stdc++.h> 
using namespace std; 
using boost::lexical_cast; 
using boost::bad_lexical_cast; 
int main() { 
  
  // integer to string conversion 
  int s = 23; 
  string s1 = lexical_cast<string>(s); 
  cout << s1 << endl; 
  
  // integer to char conversion 
  array<char, 64> msg = lexical_cast<array<char, 64>>(45); 
  cout << msg[0] << msg[1] << endl; 
  
  // string to integer conversion in integer value 
  int num = lexical_cast<int>("1234"); 
  cout << num << endl; 
  
  // bad conversion float to int 
  // using try and catch we display the error 
  try { 
    int num2 = lexical_cast<int>("52.20"); 
  } 
  
  // To catch exception 
  catch (bad_lexical_cast &e) { 
    cout << "Exception caught:" << e.what() << endl; 
  } 
  
  // bad conversion string to integer character 
  // using tru and catch we display the error 
  try { 
    int i = lexical_cast<int>("GeeksforGeeks"); 
  } 
  
  // catching Exception 
  catch (bad_lexical_cast &e) { 
    cout << "Exception caught:" << e.what() << endl; 
  } 
  
  return 0; 
}

输出:-

23
45
1234
Exception caught:bad lexical cast:source type value could not be interpreted as target
Exception caught:bad lexical cast:source type value could not be interpreted as target

参考:-http://www.boost.org/




注:本文由纯净天空筛选整理自ajay0007大神的英文原创作品 Boost.Lexical_Cast in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。