Thread: Printing a specific number of digits

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    54

    Printing a specific number of digits

    Hi all:

    Is it possible for an int to print a specific number of digits every time?

    For example:

    int x = 1;
    cout <<x <<endl; //should print 001

    x = 999;
    cout <<x <<endl; //should print 999

    Thanks.
    -Zack

  2. #2
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133
    You could just add it:
    Code:
    int x = 9;
    cout << "00" << x << endl;//009
    To work with all kinds of numbers:
    Code:
    if ( x < 10 )
    {
    
        cout << "00";
    }
    
    else if ( x < 100 )
    {
    
        cout << "0";
    }
    
    cout << x << endl;

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    54
    Ah, that works. Good thinking.

    I'm going to use that for now. However, I do recall a more elegant way of doing it (by formatting the number before printing, perhaps?). Just for my personal knowledge, does anyone know how this can be done?

    Thanks.
    -Zack

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
       for ( int i = 1; i < 1000; i *= 10 )
       {
          cout << setfill('0') << setw(3) << i << '\n';
       }
    }
    
    /* my output
    001
    010
    100
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Registered User
    Join Date
    May 2005
    Posts
    54
    Awesome. Thanks bud.
    -Zack

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. printing number from array question..
    By transgalactic2 in forum C Programming
    Replies: 41
    Last Post: 12-25-2008, 04:04 PM
  3. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  4. Number Guessing
    By blacknapalm in forum C Programming
    Replies: 2
    Last Post: 10-01-2008, 01:48 AM
  5. reverse a number digits
    By tootoo in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2007, 11:24 AM