在看代码的时候发现在获取网络端口的时候,得到的是整数,想以string的形式存储,进行的类型转换。
lexicial_cast库进行“字面量”的转换,可以进行字符串、整数/浮点数之间的字面转换。
位于名字空间boost,需要包含头文件
#include <boost/lexcical_cast.hpp>
#include <string>
using namespace boost;
using namespace std;
int main(void)
{
int x = lexicical_cast<int> ("1000"); //字符串->整数
long y = lexicical_cast<long> ("2000"); //字符串->长整型
string str = lexicical_cast<string>(456);//整数->字符串
cout << x << y << endl;
cout << str << endl;
}
注意事项:要转换成数字的字符串只能有数字和小数点,不能出现字母或其他非数字字符。
提到类型转换,当然还有标准库中的< sstream>,它定义了三种类:istringstream ostringstream stringstream 分别进行流的输入、输出、输入输出。
以stringstream为例,
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream stream;
string result;
int i = 500;
stream << i; //输入到流中
stream >> result;//流中数据输出到string
cout << result << endl;
return 0;
}
可以将各种基本类型int ,float ,long string 的转换,还支持char *,可以用来代替sprintf,而且比sprintf更加安全。
在进行多次转换的时候,需要调用stringstream的成员函数clear()来清楚stringstream。
stringstream stream;
int first,second;
stream << "123";
stream >> first; //转换为int
cout << first << endl;
stream.clear()
stream << true;
stream >> second; //bool转换为int