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

由於時間有限,沒有研究利弊,敬請各位指教。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM