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

来源:互联网 发布:大数据时代面临的挑战 编辑:程序博客网 时间:2024/05/16 12:14

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
原创粉丝点击