lexical_cast
是一个通用的类型转换工具。可以使用 boost::lexical_cast
来尝试将任何类型的值(只要它们可以通过文本形式表示)转换为任何其他类型,只要这种转换在逻辑上是有意义的。
boost::lexical_cast
的工作原理基本上是这样的:
- 将源类型转换为一个字符串表示。
- 使用目标类型的输入操作符(例如
operator>>
)尝试从该字符串中读取值。 - 如果读取成功,则返回转换后的值;如果失败,则抛出一个
boost::bad_lexical_cast
异常。
因此,可以使用 boost::lexical_cast 来执行各种类型转换,例如:
int i = boost::lexical_cast<int>("123");
double d = boost::lexical_cast<double>("3.14159");
std::string s = boost::lexical_cast<std::string>(123); // 将整数转换为字符串
这也太好用了,真是 古希腊掌管类型转换的神
完整代码
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main()
{
// Demo of basic lexical_cast usage
try
{
int i = boost::lexical_cast<int>("123");
std::cout << "Integer: " << i << std::endl;
double d = boost::lexical_cast<double>("3.14159");
std::cout << "Double: " << d << std::endl;
std::string s = boost::lexical_cast<std::string>(123);
std::cout << "String: " << s << std::endl;
}
catch (boost::bad_lexical_cast const &e)
{
std::cerr << "Error: Lexical cast failed: " << e.what() << std::endl;
}
catch (std::exception const &e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
输出内容
Integer: 123
Double: 3.14159
String: 123