Convert float to std::string in C++

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

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 

回答1:

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

std::ostringstream ss; ss 

If you're okay with Boost, lexical_cast is a convenient alternative:

std::string s = boost::lexical_cast<:string>(myFloat); 

Efficient alternatives are e.g. FastFormat or simply the C-style functions.



回答2:

As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.



回答3:

You can define a template which will work not only just with doubles, but with other types as well.

template  string tostr(const T& t) {     ostringstream os;     os

Then you can use it for other types.

double x = 14.4; int y = 21;  string sx = tostr(x); string sy = tostr(y); 


回答4:

Use to_string(). (available since c++11)
example :

#include     #include     using namespace std; int main () {     string pi = "pi is " + to_string(3.1415926);     cout

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val); 


回答5:

You can use std::to_string in C++11

float val = 2.5; std::string my_val = std::to_string(val); 


回答6:

If you're worried about performance, check out the Boost::lexical_cast library.



回答7:

This tutorial gives a simple, yet elegant, solution, which i transcribe:

#include  #include  #include   class BadConversion : public std::runtime_error { public:   BadConversion(std::string const& s)     : std::runtime_error(s)     { } };  inline std::string stringify(double x) {   std::ostringstream o;   if (!(o 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!