在C ++中将浮点数转换为std :: string [英] Converting a float to std::string in C++

查看:190
本文介绍了在C ++中将浮点数转换为std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个看似简单的问题,但我很难提出答案。我有一个float值,需要放入std :: string,如下:

This is a seemingly simple problem, but I'm having difficulty coming up with an answer. I have a float value that needs to be put into a std::string, like so:

float val = 2.5;
std::string my_val = val; // error here

显然它们有不同的类型。如何从float转换为字符串?

Obviously they're of different types. How do I convert from float to string?

所有的帮助都很感激。

推荐答案

除非您担心效果,请使用字符串流

Unless you're worried about performance, use string streams:

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 ++中将浮点数转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆