C++ boost::lexical_cast

1. lexical_cast is a library in boost, which is mainly used to convert between numeric values ​​and strings. Boost's lexical_cast can convert strings into various C++ built-in types, and header files need to be included:

#include <boost/lexical_cast.hpp>
using namespace boost;

2. The lexical_cast library performs "literal" conversion, similar to the atoi function in C language, which can convert between character strings, integers and floating-point numbers. The format used is:

Insert picture description here

T is a data type or template template customization (a type known only by instantiation)

3. When using lexical_cast, pay attention to the fact that the string to be converted into a number can only have numbers and decimal points, and no letters (except e/E for exponents) or other non-digit characters, that is to say, lexical_cast cannot be converted such as "123L ", "0x100", such as digital literal string permitted by C++ syntax.

int value=boost::lexical_cast(“123”)
float value=boost::lexical_cast(“1.2”)

4. When lexical_cast cannot perform the conversion operation, it will throw an exception bad_lexical_cast

terminate called after throwing an instance of ‘boost::exception_detail::clone_impl<boost::exception_detail::error_info_injectorboost::bad_lexical_cast >’
what(): bad lexical cast: source type value could not be interpreted as target

For example, the value of atoi("2.5") is 2, and boost::lexical_cast("2.5") will throw an exception of boost::bad_lexical_cast, so we need to use try/catch to protect the conversion.

try
{
int i = boost::lexical_cast(“12.3”);
}
catch (boost::bad_lexical_cast& e)
{
cout << e.what() << endl;
}

5. For example, in the STL library, we can use stringstream to achieve the conversion between strings and numbers:

int i = 0;
stringstream ss;
ss << “123”;
ss >> i;

But stringstream has no error checking function. For example, for the following code, i will be assigned to 12.

ss << “12.3”;
ss >> i;

In order to solve this problem, you can use boost::lexical_cast to achieve numerical conversion:

int i = boost::lexical_cast(“123”);
double d = boost::lexical_cast(“12.3”);

note!
When reading a text file, there may be "\r" or "\n" identifiers after the string, which needs to be removed using the trim function

Guess you like

Origin blog.csdn.net/weixin_41169280/article/details/110000325
Recommended