My program is supposed to take in an interger, and tell me if it's a prime number or not. If I enter something like "woof", it'll tell me that it is invalid and does not work.
My program is as follows:
Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int is_prime(int n)
{
int b;
if(n<2)
return 0;
for(b = 2; b<=sqrt(n); b++)
{
if (n%b==0)
{
return 0;
}
}
return 1;
}
int read_an_int(void)
{
int a, ret, c;
while(1)
{
ret = scanf("%d", &a);
if(ret == EOF)
return -999;
if(ret == 1)
return a;
printf("Invalid input, please try again: \n");
while((c = getchar()) != '\n' && c != EOF)
;
continue;
}
}
int main(void)
{
int a, ret;
while (1)
{
printf("Enter a number to test (negative number to stop): \n");
ret = read_an_int();
if(ret==-999)
printf("End of file.");
if(ret==a)
{
if (a<0)
{
printf("Bye!\n");
break;
}
if(is_prime(a) == 1)
printf("%d is prime\n", a);
else
printf("%d is not prime\n", a);
}
}
return 0;
}
When I try to compile it, the printf statement works, but if I try a number, it won't tell me if it's prime or not. I tried to put in woof, and that does indeed tell me that what I entered is invalid and that I need to enter another number.
In other words, it scans in my function called read_an_int, but for some reason it doesn't read in the part where I have to say if it's a prime number or not.
like if(ret==a) and so on. Anyone know how I can fix it?