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 << " , " ;

}``````
4
Contributors
3
Replies
6
Views
7 Years
Discussion Span
Last Post by firstPerson

put the difigits in an array then sort the array.

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.

Edited by WaltP: n/a

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] << " ";
}
*/
}``````