1 字符串→数值
下面先讨论一下从字符串类型到数值类型的转换。
如何将字符串”123”转换为int类型整数123?答案是,用标准C的库函数atoi;
如果要转换为long类型呢?标准C的库函数atol;
如何将”123.12”转换为double类型呢?标准C的库函数atod;
如果要转换为long double类型呢?标准C的库函数atold;
……
使用Boost Conversion Library所提供的函数lexical_cast(需要引入头文件boost/lexical_cast.hpp)是最简单方便的。如:
#include <boost/lexical_cast.hpp>
#include <iostream>
using namespace boost::lexical_cast;
int main(){
double b = lexical_cast<double>("123.12");
std::cout<<a<<std::endl
std::cout<<b<<std::endl;
return 0;
}
一个函数就简洁地解决了所有的问题。
2 数值→字符串
那么从数值类型到字符串类型呢?
用itoa?不对吧,标准C/C++里根本没有这个函数。即使在Windows平台下某些编译器提供了该函数3,没有任何移植性不说,还只能解决int类型(也许其他函数还可以解决long、unsigned long等类型),浮点类型又怎么办?当然,办法还是有,那就是:sprintf。
char s[100];
sprintf(s, "%f", 123.123456);
lexical_cast的#include
#include <string>
#include <iostream>
using namespace std;
int main(){
string s = boost::lexical_cast<string>(d);
std::cout<<s<<std::endl;
return 0;
}
跟前面一样简单。