在C ++中将float转换为std :: string

编程入门 行业动态 更新时间:2024-10-27 12:30:08
本文介绍了在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

本文发布于:2023-05-27 03:04:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/275506.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   string   float   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!