Showing posts with label Get number input using C Program. Show all posts
Showing posts with label Get number input using C Program. Show all posts

Friday, December 11, 2015

Get number input using C Program


Program #20

Description:
Get number [0-9] only as input from the user.  Even if user press characters, system will ignore and wait for valid input.  Once input reaches MAXLENGTH (user defined length) program will stop the execution.


#include<stdio.h>
#include<conio.h>
#include<dos.h>

/* user defined Constant to restrict max length */
#define MAXLENGTH 10

/* Global String Array */
char userInput[MAXLENGTH];
int main(){
 int i, charCounter=0;
 char c=' ';

 /* prototype declaration */
 void printReceivedInputs(int);

 clrscr();
 printf("\n!Important: Maximum %d valid characters only.\n", MAXLENGTH);
 for(i=1; i<46; i++){
   printf("-");
   delay(100);
 }
 printf("\nPlease Enter Integer value [0-9]:\n");

 for(;!kbhit();){
    c = getch();

    /* Stop getting input, If user press below keys
     Enter Key - 13
     ESC Key   - 27
     TAB Key   -  9
     Space Bar - 32
     Backspace -  8
    */

    if (charCounter == MAXLENGTH){
      printf("\n\n\nThanks for your Input!\n");
      for (i=0; i<22; i++){
 printf("_");
 delay(100);
      }
      break;
    } else if (c == 13 || c == 27 || c == 9 || c == 32 || c == 8){
      printf("\nUser Intruption !!");
      getch();
      return 0;
    }
   
/* Accept only Numbers, else ignore */
    else if (c >= 48 && c <= 57){
      userInput[charCounter++] = c;
     
/* Dynamically print the user input */
      printReceivedInputs(charCounter);
    }
 }

 printf("\n\nInput #\n%s", userInput);
 getch();
 return 0;
}

void printReceivedInputs(int charLen){
  int i;
  gotoxy(15,8);
 
  /* Clear the Output area */
  printf("          ");
 
  /* Start to print on perfect position */
  gotoxy(15,8);
  for (i=0; i<charLen; i++){
    printf("%c",userInput[i]);
  }
}


 

 

Popular Posts