本文介绍了在C ++中将float转换为std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个浮点值,需要将其放入 std :: string 中。如何从float转换为字符串?
I have a float value that needs to be put into a std::string. How do I convert from float to string?
float val = 2.5; std::string my_val = val; // error here推荐答案
除非您担心性能,请使用字符串流:
Unless you're worried about performance, use string streams:
#include <sstream> //.. std::ostringstream ss; ss << myFloat; std::string s(ss.str());如果您对Boost没问题,请 lexical_cast<> 是一种方便的选择:
If you're okay with Boost, lexical_cast<> is a convenient alternative:
std::string s = boost::lexical_cast<std::string>(myFloat);高效的替代方案例如 FastFormat 或只是C风格的函数。
Efficient alternatives are e.g. FastFormat or simply the C-style functions.
更多推荐
在C ++中将float转换为std :: string
发布评论