web analytics

Conveting double to string using stringstream in C++

Options

davegate 143 - 921
@2016-01-27 13:00:34

The follwing C++ code demonstrates how to convert a double to string using stringstream. We also use two manipulators setiosflags and setprecision to ensure the code behave correctly.

#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;

void main()
{
 double d = 1600564.00;

 stringstream ss;
 ss << setiosflags(ios::fixed) << setprecision(2) << d;

 string str = ss.str();

 ss.clear();

}
@2016-01-27 13:03:21

The following C++ code can do the same thing.

 //using sprintf
 char str2[11] = "\0";
 sprintf(str2, "%.2f", d);

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com