数值与字符串之间的转换:lexcical_cast 和sstream

在看代码的时候发现在获取网络端口的时候,得到的是整数,想以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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值