Sunday, September 5, 2010

Y2S2 sharing 2 (Integer input function for C )

For Engineering computing subject. Actually we studied C-programing in this subject. For debugging the integer input problem. I had created one function for prompt integer. If not integer. Error message will displayed:

Example are as below:

# include
# include
int ulti_input();
int main()
{
printf("%d\n",ulti_input());
}


int ulti_input()
{
int digit,i,cond,cnum=2,number,cnum2=1,digit2,alpha,fault;
char num[20]={0};
do
{
gets(num);
number=atof(num);
cnum=num[0];// for first bit of array
alpha=isalpha(num[0]);
digit=isdigit(num[0]);
cnum2=1;
fault=num[1];

/*
-if" function here used to check the first bit of array so if first bit detected is digit then ""for" loop below will activated to check the following bit until detected null bit.
-if first bit is not a digit or is not '+'and'-'and is NULL then it will stop checking second bit of array by displaying eror message then prompt for new input again
-if first bit is '+'or'-' then will check for the second bit whether is 'NUL' or not. If it is null then error message will dispayed and prompt for new input again
-else if fist bit is '+' or '-' then "for loop" below will be activated for scaning until its detected NULL bit then integer entered will be returned.
*/
if(cnum==0/*||alpha==2*/||digit==0)// if first bit of array equal to NUL or is not a digit will enter this if function
{
if(num[0]=='-'||num[0]=='+')
{
if(fault==0)// fault here is for if second bit is null then error message will dipayed and prompt for new input
{
cond=1;//give true to do while loop
cnum2=0;// cnum2 is conditio for "for loop" below.. condition here give false to disable the for loop below
printf("\nInvalid input!!!\nYour input is not an integer...\n");// display error message
}
}
else //if not + or - and is not a digit then "for loop" below will be disable and will prompt for new input
{
cnum2=0;// cnum2 is conditio for "for loop" below.. condition here give false to disable the for loop below
cond=1;//give true to do while loop
printf("\nInvalid input!!!\nYour input is not an integer...\n");
}
}
for(i=1;cnum2!=0;i++)// this for loop is used to check bit start from second bit of array memories.
{
cnum=num[i];
if(cnum==0)// if NUL detected. converted number will return to main
{ //printf("\n-%d-\n",number);<---unlock this to check input returned
return number;
}
else// if Null not detected then for loop will continue running
{

digit=isdigit(num[i]);}//check array bit is in digit or not

if (digit==0)// if not digit give true
{
printf("\nInvalid input!!!\nYour input is not an integer...\n");
cnum2=0;//disable the "for loop"
cond=1;//give true to "do-while" condtion
}
else ;// if is digit "for loop" will continue running
}// end of for loop

printf("please enter an interger:");
}
while(cond==1);



}



//end of ulti_iput() function

No comments: