double, long, int ==> string conversion

This is a discussion on double, long, int ==> string conversion within the C++ Programming forums, part of the General Programming Boards category; Hope someone can tell me how to convert from double, long and int to a string of a specified length. ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    19

    double, long, int ==> string conversion

    Hope someone can tell me how to convert from double, long and int to a string of a specified length. I also need to to pad the string with zeros.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,803
    An example converting an int value:
    Code:
    #include <sstream>
    #include <string>
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
        ostringstream ostr;
        string str;
        int iVal = 157;
    
        // Convert int value into string value with '0' padding to 7 places
    
        ostr << setw(7) << setfill('0') << iVal;
        str = ostr.str();
    
        // Output string
    
        cout << str << endl;
    
        return 0;
    }
    Output:
    Code:
    0000157
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  3. Replies: 26
    Last Post: 11-30-2007, 02:51 AM
  4. Moving Average Question
    By GCNDoug in forum C Programming
    Replies: 4
    Last Post: 04-23-2007, 11:05 PM
  5. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21