How to use lexical_cast In C++
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.
Syntax:
float x= 5.5; string res = lexical_cast<string>(x);
Example:
C++
#include "boost/lexical_cast.hpp" #include <bits/stdc++.h> using namespace std; using boost::lexical_cast; using boost::bad_lexical_cast; int main() { // Float to string conversion float x= 5.5; string res = lexical_cast<string>(x); cout << res << endl; return 0; } |
Output:
5.5
Convert Float to String In C++
In this article, we learn how we can convert float to string in C++ using different methods:
- Using the to_string()
- Using stringstream
- Using Macros
- Using lexical_cast from the boost library
Contact Us