Skip to content
Related Articles

Related Articles

Boost.Lexical_Cast in C++
  • Difficulty Level : Medium
  • Last Updated : 26 Apr, 2018

Boost.LexicalCast which is defined in the Library “boost/lexical_cast.hpp” provides a cast operator, boost::lexical_cast, that can convert numbers from strings to numeric types like int or double and vice versa.

boost::lexical_cast is an alternative to functions like std::stoi(), std::stod(), and std::to_string(), which were added to the standard library in C++11.
Now let see the Implementation of this function in a program.

Examples:

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

Associated exceptions : If a conversion fails, an exception of type bad_lexical_cast, which is derived from bad_cast, is thrown. It throws an exception because the float 52.50 and the string “GeeksforGeeks” cannot be converted to a number of type 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;
}

Output:-

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

Reference :- http://www.boost.org/

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :