C++:float 转型到 std::string

1、利用boost中的format类去实现。如下:

cout << format( "%1% says \"%2%\" to %1%.\n" ) % "Yousen" % "Hello";

这句话将在标准输出上输出“Yousen says "Hello" to Yousen.”
接下来简单说明一下format的用法。在格式化字符串中,“%1%”(不带引号,后称占位符)表示后面跟的第一个参数,“%2%”则 表示第二个,以此类推——注意:占位符是从1开始计数。后面的“%”是format类重载的操作符,用来跟占位符中的字符串。
刚才说了,format是个类,确切的说format是这样定义的:

typedef basic_format<char> format;

看清楚了哦,要想用unicode(宽字符)版的format,就用wformat。

typedef basic_format<wchar_t> wformat;

现在来试试format的实例:

#include <boost/format.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace boost;

int main()
{
	format fmt( "%2% says \"%1%\"." );
	fmt % "Yousen";
	fmt % "Hello";
	string str = fmt.str();
	cout << "string from fmt: " << str << endl;
	cout << "fmt: " << fmt << endl;
}
输出:

string from fmt: Hello says "Yousen".
fmt: Hello says "Yousen".

2、使用boost中的boost::lexical_cast<>()进行转换。使用方法如下:

float f;
std::string s;
f  = boost::lexical_cast<float>(s);
s = boost::lexical_cast<std::string>(f);

3、使用std中的sstream进行转换。使用如下:

#include <sstream>
#include <iostream>
using namespace std;   
int main()   
{  
    ostringstream buffer;
    float f = 4.555555558;
    buffer << f;
    string str = buffer.str();
    cout<<str<<endl;
}
4、使用库stdlib中的gcvts函数。

 

#include <iostream>
using namespace std;   
int main()   
{  
    char str[50];
    double source = 1118.726521;
    _gcvt_s(str, 50, source, 20);
    std::cout<<str<<std::endl;
    system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值