CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Sep 2003
    Posts
    815

    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.

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    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;
    }
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  3. #3
    Join Date
    Sep 2003
    Posts
    815
    what do you think is better
    using this or using sprintf
    (I mean performance)

    thanks

  4. #4
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    You should only worry about performance if you've discovered a performance problem. Your concern should be maintenance, not performance.

    This is better.

    Jeff

  5. #5
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    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
  •  





Click Here to Expand Forum to Full Width

Featured