Marelisse Marelisse - 29 days ago 6
C Question

how to check if the number is not an integer in C without using isdigit?

I've been writing a code of the Fibonacci sequence (iteratively). It scans a number n, and it outputs F(n) until I input -1. The problem is that first, I need to check if the number is not an integer. If it is not an integer, it should output "error".

#include<stdio.h>
#include<ctype.h>

int main(){
float n=0;
int x=0,ver=0,Fn=0,last1=0,last2=0;

scanf("%f",&n);
ver=n;
while(n!=-1){
if(n-ver!=0 || !isdigit(ver)){
printf("Error\n");
}
else if(n==1 || n==2){
printf("1\n");
} else{
last1=1;
last2=1;
for(x=3;x<=n;x++){
Fn=last1+last2;
last1=last2;
last2=Fn;
}
printf("%d\n",Fn);
}
getchar();
scanf("%f",&n);
ver=n;
}
return 0;
}


I've tried with isdigit and !isdigit and I still get wrong outputs. It should output error when I input things like .11$, 1.- , 1.23,KDhf, etc.

usr usr
Answer

For finding fibonacci numbers, you don't need n to be of float type. You can use any integer type.

To find if the number was scanned successfully, check the return value of scanf().

int n = 0;
if (scanf("%df",&n) != 1) {
    printf("Error\n");
    exit(EXIT_FAILURE);
}

And remove this part:

    if(n-ver!=0 || !isdigit(ver)){
        printf("Error\n");
    }

isdigit() can only handle single digit numbers.

Comments