📜  C++中的Boost.Lexical_Cast

📅  最后修改于: 2021-05-30 14:55:17             🧑  作者: Mango

在库“ 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 
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(s);
  cout << s1 << endl;
  
  // integer to char conversion
  array msg = lexical_cast>(45);
  cout << msg[0] << msg[1] << endl;
  
  // string to integer conversion in integer value
  int num = lexical_cast("1234");
  cout << num << endl;
  
  // bad conversion float to int
  // using try and catch we display the error
  try {
    int num2 = lexical_cast("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("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/

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”