C++:float 转型到 std::string 之总结。

看起来,float转型string,std中没有提供标准的方法。查阅了些资料。总结如下:

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");
}   

由于时间有限,没有研究利弊,敬请各位指教。

本文版权归作者 kanego 和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文地址:https://www.cnblogs.com/kanego/p/2578748.html