I have written following code to get an integer from keyboard.
It will prompt an Error message until you give a valid integer value (either negative or positive ).
One condition is It has to check every possible test cases
like:
-3.2
5.0
984237.4329
0.343
.434
12344.
adfs34
233adds
3892710492374329
helloIamNotainteger
For all of this tests it should fail.It will pass only for int >=INT_MIN && int <=INT_MAX
value.
My Running code is :
#include<stdio.h>
#include<limits.h>
int min=INT_MIN;
int max=INT_MAX;
int main()
{
char str[50],c; //I have taken size 50 please ignore this
int check;
do
{
int flag=1,i=0,j=0,num=0;
check=0;
printf("Enter an Integer : ");
while((c=getchar())!='\n')
str[i++]=c;
if(str[0] == '-')
{
flag = -1;
j++;
}
for(;j<i;j++)
{
if(str[j] >= '0' && str[j] <= '9')
num=(str[j]-'0') + num*10;
else
break;
}
if(j<i)
{
printf("Not an Integer, Please input an integer \n");
}
else if(num < min || num >max)
{
printf("Integer is out of range,Please input an integer \n");
}
else
{
num *=flag;
printf("The given number is : %d\n",num);
check=1;
}
}while(check == 0);
return 0;
}
One example : For values like this.
83429439803248832409 (It’s integer but it should fail because of range )but it passes and give some other integer value.
How to solve this within my code or any better idea to implement getInt() ?
Here is the working code : please see this , I did that wihtout
strtoland it satisfies all conditions and takes onlyint