看起來,float轉型string,std中沒有提供標准的方法。查閱了些資料。總結如下:
1、利用boost中的format類去實現。如下:
這句話將在標准輸出上輸出“Yousen says "Hello" to Yousen.”
接下來簡單說明一下format的用法。在格式化字符串中,“%1%”(不帶引號,后稱占位符)表示后面跟的第一個參數,“%2%”則 表示第二個,以此類推——注意:占位符是從1開始計數。后面的“%”是format類重載的操作符,用來跟占位符中的字符串。
剛才說了,format是個類,確切的說format是這樣定義的:
看清楚了哦,要想用unicode(寬字符)版的format,就用wformat。
現在來試試format的實例:
#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");
}
由於時間有限,沒有研究利弊,敬請各位指教。