Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Rread a number input from the keyboard and then put each of its components in an array

2.00/5 (1 vote)
31 May 2010CPOL 8.3K  
Description of how to read a number input from the keyboard and then put each of its components in an array
It reads a number from CMD [For example: 1234].
Then puts each of its components in an array - digitArray[3]=1, digitArray[2]=2, digitArray[1]=3, digitArray[0]=4 .




   //         one                ten              hundred              thousand
   //          1                  2                  3                    4
   //digitn=digitArray[3]*1 + digitArray[2]*10 +digitArray[1]*100 +digitArray[0]*1000

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>


int digit=0,digitInput=0;
int digitArray[4]={0},digitn;
 
/*********************************
 *                               *
 ********************************/

void getIntKey(void)
{
   digitArray[0]=0;
   digitArray[1]=0;
   digit=0;
   digitInput=0;

   while((digit<4))
   {
	   if (kbhit())
	   {
		   digitInput=getch();
		 
		   if ((digitInput>47) && (digitInput<59))
		   {
	                 digitArray[digit]=(unsigned char)digitInput-48;
			 digit++;
			   
		   }
		   if (digitInput==13)  { digitn=digitArray[0]; break; }
	   }
   }
   if (digitInput!=13)  digitn=digitArray[3]*1+digitArray[2]*10+digitArray[1]*100+digitArray[0]*1000 ;
   printf("\n%i\n\n",digitn);
}

/*********************************
 *                               *
 ********************************/

int main()
{
	system("color 1F");     //Blue background       
   printf("This program by TopCoder requires you to input 4 digits  \n ");
   printf("Input Digits  (ex. 1=0001 , 1234=1234)  \n ");
   printf("\nInput Digits    >");
   getIntKey();
   
   printf("\ndigitArray[3]=%d \n",digitArray[3]);
   printf("digitArray[2]=%d \n",digitArray[2]);
   printf("digitArray[1]=%d \n",digitArray[1]);
   printf("digitArray[0]=%d \n",digitArray[0]);
   printf("\n%i\n\n",digitn);




	return 0;
}


..

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)