由float轉std::string的方法


std標准庫中沒有提供標准的方法,查閱資料,總結了兩種僅僅在標准庫支持下的轉換方法:

1. 使用std中的sstream進行轉換

 1 #include <stdio.h>
 2 #include <sstream>
 3 #include <string>
 4 
 5 std::string getStringFromFloat(float f)
 6 {
 7     std::ostringstream buffer;
 8     buffer << f;
 9     return buffer.str();
10 }
11 
12 int main(int, char**)
13 {
14     float f = 3.14f;
15     printf("the %f convert to string style: \"%s\".\n", f, (getStringFromFloat(f)).c_str());
16     return 0;
17 }

Result:

the 3.140000 convert to string style: "3.14".

 

2. 使用stdlib中的_gcvt_s()函數

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string>
 4 
 5 // 第二個參數表示返回的位數
 6 std::string getStringFromFloat(float f, int bits)
 7 {
 8     char buffer[50];
 9     _gcvt_s(buffer, sizeof(buffer), f, bits);
10     return buffer;
11 }
12 
13 int main(int, char**)
14 {
15     float f = 3.14f;
16     printf("the %f convert to string style: \"%s\".\n", f, (getStringFromFloat(f, 3)).c_str());
17     return 0;
18 }

Result:

the 3.140000 convert to string style: "3.14".

讀者可以測一下這兩個函數所有的時間,才選擇相應的方法,其他的方法(如使用boost庫中的函數)就不再記述了。

 

由字符串轉浮點數字大家喜歡用atof()函數。在使用Microsoft C/C++開發應用程序時,sscanf()函數很好地替代 atof() 函數,將數字字符串轉換為浮點數。如果字符串表示的數無效,atof() 將返回零值,而 sscanf() 會返回更多有用的錯誤信息。應用程序可以將 sscanf() 返回的錯誤值用於 matherr() 函數以執行錯誤處理。除非真正發生了數學異常,否則 atof() 函數不會調用 matherr()。

下文提供了兩種將字符串轉換為浮點數的推薦辦法。

  • 在調用 atof() 函數前驗證要轉換的字符串。確保字符串中不包含任何非數值字符,而且小數點和正負號的位置都正確。
  • 使用 sscanf() 函數。它比 atof() 函數慢,但在發生錯誤時可以提供更詳細的信息。

參考博客:

http://www.cnblogs.com/kanego/archive/2012/07/06/2578748.html

ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/kb/visualc/11558.htm

 

使用sstream轉換基本類型非常方便,可參考博文:

http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html


免責聲明!

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



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