由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".
", 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".
", 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

原文地址:https://www.cnblogs.com/yooyoo/p/4717919.html