Pages

Tuesday, August 13, 2013

Write a program that Print six digits with commas in C++

This program reads long integers from the keyboard and prints them with leading
zeros in the form 123,456 with a comma between the 3rd & 4th digit

Source Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
   #include <iostream>
   #include <conio.h>
   #include <iomanip.h>
   using namespace std;
   // Prototype declarations
   void printWithComma (long num);
   int main ()
   {
       cout << " Enter a number with upto 6 digits: ";
       long number;
       cin  >> number;
       printWithComma (number);
       return 0; 
              } // main
    /* ============= printWithComma ========================
    This function divides num into two three digit numbers 
    and prints them with a comma inserted
        Pre  num is six-digit number
        Post num has been printed with a comma inserted    */ 
        
    void printWithComma (long num)
    {
         float thousands = num / 1000;
         float hundreds  = num % 1000;
         cout << "\n The number you entered is \t";
         cout << setw(3) << thousands <<" , ";
         cout << setfill('0');
         cout << setw(3) << hundreds;
         getch ();
         return ;
                 }// printWithComma

Result:

 Enter a number with upto 6 digits: 123456

 The number you entered is 123,456

No comments:

Post a Comment