How do I convert a double into a string in C++?

2019-01-01 14:21发布

I need to store a double as a string. I know I can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).

17条回答
余生请多指教
2楼-- · 2019-01-01 15:01

You could try a more compact style:

std::string number_in_string;

double number_in_double;

std::ostringstream output;

number_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<

std::endl)))->str(); 
查看更多
柔情千种
3楼-- · 2019-01-01 15:04

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

查看更多
初与友歌
4楼-- · 2019-01-01 15:05

The Standard C++11 way (if you don't care about the output format):

#include <string>

auto str = std::to_string(42.5); 

to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) "Simple Numeric Access". There are also the stod function to perform the reverse operation.

If you do want to have a different output format than "%f", use the snprintf or ostringstream methods as illustrated in other answers.

查看更多
高级女魔头
5楼-- · 2019-01-01 15:06

I would look at the C++ String Toolkit Libary. Just posted a similar answer elsewhere. I have found it very fast and reliable.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );
查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 15:09

Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.

查看更多
梦醉为红颜
7楼-- · 2019-01-01 15:10

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}
查看更多
登录 后发表回答