-
December 9th, 2003, 09:35 AM
#1
another question about stl and sprintf
If I have for example a double holding the value 128.65 and I want to present it as 128.650000
than I can do
sprinf(szStr,"%.10f,myDouble)
I tried using your advice and use std::stringstream
but what I managed to do is getting 0000128.65
what I did is:
std::stringstream buffer;
buffer.fill('0');
buffer << std::setw(nLen) << dValue;//nLen is the required length
//in this example it's 10
*psDest = buffer.str();
Can you pls show me how to do that?
thanks
avi
Last edited by avi123; December 9th, 2003 at 09:40 AM.
-
December 9th, 2003, 10:15 AM
#2
Code:
#include <sstream>
#include <iomanip>
int main()
{
std::stringstream ss;
double d = 218.65;
ss<<std::setfill('0')<<std::left<<std::setw(10)<<d<<std::endl;
std::cout<<ss.str();
return 0;
}
-
December 9th, 2003, 10:20 AM
#3
what do you think is better
using this or using sprintf
(I mean performance)
thanks
-
December 9th, 2003, 11:38 AM
#4
You should only worry about performance if you've discovered a performance problem. Your concern should be maintenance, not performance.
This is better.
Jeff
-
December 9th, 2003, 12:00 PM
#5
Code:
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
string write_double(double d, int width, int precision)
{
stringstream ss;
ss << setw(10) << setprecision(6) << d;
return ss.str();
}
int main()
{
string s = write_double(128.65, 10, 6);
}
There's also a manipulator for doing the equivalent of the g, f and e format specifiers, but I can't remember what it is offhand (the default is to output like %g).
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|