boost::lexical_cast

boost::lexical_cast

c++ 使用 boost::lexical_cast 数据类型转换

参考链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#define ERROR_LEXICAL_CAST 1
int main()
{
using boost::lexical_cast;
int a = 0;
double b = 0.0;
std::string s = "";
int e = 0;
try
{
// ----- 字符串 --> 数值
a = lexical_cast<int>("123");
b = lexical_cast<double>("123.12");
// ----- 数值 --> 字符串
s = lexical_cast<std::string>("123456.7");
// ----- 异常处理演示
e = lexical_cast<int>("abc");
}
catch(boost::bad_lexical_cast& e)
{
// bad lexical cast: source type value could not be interpreted as target
std::cout << e.what() << std::endl;
return ERROR_LEXICAL_CAST;
}
std::cout << a << std::endl; // 输出:123
std::cout << b << std::endl; // 输出:123.12
std::cout << s << std::endl; // 输出:123456.7
return 0;
}