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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:53:33  来源:igfitidea点击:

convert float to string

c++stringfloating-point

提问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 Liv

Can you not use the standard (C) function sprintf/fprintf etc?

您不能使用标准(C)函数 sprintf/fprintf 等吗?

回答by Drahakar

回答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 ostringstreamfor this. Boost's lexical_castwraps the string streams in an easy-to-use fashion.

如果没有,并且您确实需要一个字符串,则可以ostringstream为此使用一个。Boostlexical_cast以易于使用的方式包装字符串流。