954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

digits on the screen separately

Hi ,
I've written following program that takes a four digits integer from user and shows the digits on the screen separately i.e. if user enters 7531, it displays 7,5,3,1 .Any one can tell me how it can be written better and how to display digit in linear order i.e. if user enters 7531, it displays 1,3,5,7 .Thanks

#include <iostream> 
using namespace std ;
main()
 
{       
           // declare variables 
           
           int number, digit;  
  
          // prompt the user for input
           
          cout << "Please enter 4-digit number:"; 
          cin >> number; 
  
        // get the first digit and display it on scree
       
          digit = number % 10; 
          cout << "The digits are: " << digit << " , ";   
 
  
            // get the remaining three digits number 
            
          number = number / 10; 
      
          // get the next digit
           
          digit = number % 10; 
          cout << digit << " , " ;
             
          // get the next digit    
          
          number = number /10 ;
          digit = number % 10 ;
          cout <<digit << " , " ;
          
          // get the remaining digit
          
          number = number /10 ;
          digit = number % 10 ;
          cout <<digit << " , " ;
                 
                 
             
  }
naseerhaider
Newbie Poster
13 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

put the difigits in an array then sort the array.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

To make the program better, put the 'work' in a loop. That way you only need one % and /. When the number is 0 the loop is finished.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Suggestion is to use std::string and std::sort. Its just a few liner :

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
 std::string input;
 cin >> input; //get input
 std::sort(input.begin(),input.end()); //sort it
 cout << input << endl; //print it
 //or access each element like so 
 /*
     for(int i = 0; i < input.size(); ++i){ 
        cout << str[i] << " ";
     }
 */
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: