Scan a Valid Integer value

Hi Everyone…

As you all know that in C there is no function that can validate the entered string as an correct integer. Whenever you enter ’12d3′ where an integer value is expected your program will through an exception. In order to cope with this I wrote the following function and tried to consider every possiblity (-ve integers, +ve integers, backspace while entering character and other alpha numeric characters….). I have written this function using Turbo C/C++ 3.0 compiler.  

I have also written functions for others (long integer, float, double) tell me if you want any of them or just change the one given below. 😉 

1. How to use this function:

Create either a header file and put this function there or just copy paste this function in your source file and call this function where you want to read an integer from user…e.g.

int main ()

{

int i;

printf (“Please Enter an Integer: “);

i = short_integer();

printf (“You entered %d”, i);

}

// Definition for short_integer function goes here after you main

2. Listing for short_integer function

 int I,J,C;

char CH,*string;

char text[4096];

int short_integer()

{

int y=wherey(),x=wherex();

long number;

check:

J=0;

C=0;

for (I=0; I<=20; I++)

string[I]=NULL;

gotoxy (x,y);

while ((CH=getch())!=’\r’)

{

if (isdigit(CH) && J<=4 || CH==’-‘)

{

printf (“%c”,CH);

C=1;

string[J]=CH;

J=J+1;

}

else if (CH==’\b’)

{

string[–J]=NULL;

if (J>=0)

{

printf (“\b \b”);

if (J==0)

C=0;

}

else if (J<=0)

{

J=0;

C=0;

printf (“\a”);

}

}

else

{

if (J<=4)

printf (” \b\a”);

else

printf (“\a”);

/*gettext (1,1,80,25,text);

clrscr();

textcolor (RED+BLINK);

gotoxy (23,12); cprintf (“Wrong Integer Value Entered”);

gotoxy (25,13); cprintf (“Press Enter to ReEnter”);

while (getch()!=’\r’);

textcolor (7);

clrscr();

puttext (1,1,80,25,text);

gotoxy (y,x);

printf (” “);

gotoxy (y,x);

goto check; */

}

}

if (C==0)

goto check;

number=atol(string);

if (number>=32767)

{

/*gettext (1,1,80,25,text);

clrscr();

textcolor (RED+BLINK);

gotoxy (26,12); cprintf (“Integer Out of Range”);

gotoxy (25,13); cprintf (“Press Enter to ReEnter”);

while (getch()!=’\r’);

textcolor (7);

clrscr();

puttext (1,1,80,25,text);*/

gotoxy (x,y);

printf (” \a”);

gotoxy (x,y);

goto check;

}

return (number);

}

Keep Smiling 🙂