[英]Float64 to string
In C++, how can I convert a data of type float64 to a string without losing any of the data in float64? 在C ++中,如何在不丢失float64中的任何数据的情况下将float64类型的数据转换为字符串? I need it to not only be converted to a string, but add a string to either side of the number and then sent to be written in a file.
我不仅需要将其转换为字符串,还需要在数字的任一侧添加一个字符串,然后将其发送以写入文件中。
Code: 码:
string cycle("---NEW CYCLE ");
cycle+=//convert float64 to string and add to cycle
cycle+= "---\r\n";
writeText(cycle.c_str()); //writes string to txt file
Thanks. 谢谢。
The usual way of converting numbers to std::string
s is to use std::ostringstream
. 将数字转换为
std::string
的通常方法是使用std::ostringstream
。
std::string stringify(float value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
// [...]
cycle += stringify(data);
您可以使用sprintf
格式化字符串。
You should use sprintf
. 您应该使用
sprintf
。 See documentation here C++ Reference . 请参阅此处的C ++参考文档。
As an example it would be something like: 举个例子:
char str[30];
float flt = 2.4567F;
sprintf(str, "%.4g", flt );
Also I would use string::append
to add the string. 我也将使用
string::append
添加字符串。 See here . 看这里 。
UPDATE 更新
Updated code according to comment. 根据注释更新了代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.