C++ 将浮点数转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5793986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert float to string
提问by Jorge Vega Sánchez
Possible Duplicate:
Convert double to string C++?
可能的重复:
将 double 转换为字符串 C++?
I searched in the page but i haven't found the solution.
我在页面中搜索,但我还没有找到解决方案。
I have a method to convert from int to string. But now i need to convert from float/double to string. Because i want to write some data in a file.
我有一种从 int 转换为 string 的方法。但是现在我需要从 float/double 转换为 string。因为我想在文件中写入一些数据。
Anyone could help me ??
任何人都可以帮助我?
Thanks in advance.
提前致谢。
回答by John K.
http://www.daniweb.com/software-development/cpp/threads/146718
http://www.daniweb.com/software-development/cpp/threads/146718
#include <sstream>
std::string Convert (float number){
std::ostringstream buff;
buff<<number;
return buff.str();
}
回答by Charles Brunet
You could use sprintf.
您可以使用sprintf。
You could use stringstreamwith << operator.
您可以将stringstream与 << 运算符一起使用。
See also Convert double to string C++?, How do I convert a double into a string in C++?, Convert double to string using boost::lexical_cast in C++?, Converting Double to String in C++, etc.
另请参见将双精度转换为字符串 C++?,如何在 C++ 中将 double 转换为字符串?,在 C++ 中使用 boost::lexical_cast 将 double 转换为字符串?,在 C++ 中将 Double 转换为 String等。
回答by Liv
Can you not use the standard (C) function sprintf/fprintf etc?
您不能使用标准(C)函数 sprintf/fprintf 等吗?
回答by Drahakar
This can help you : Convert double to string C++?
这可以帮助您:将双精度转换为字符串 C++?
回答by Chris Jester-Young
Is your file written using IOStreams? If so, just do this:
您的文件是使用 IOStreams 编写的吗?如果是这样,只需这样做:
stream << number;
If not, and you really need a string, you can use an ostringstream
for this. Boost's lexical_cast
wraps the string streams in an easy-to-use fashion.
如果没有,并且您确实需要一个字符串,则可以ostringstream
为此使用一个。Boostlexical_cast
以易于使用的方式包装字符串流。