C language, how can I check if a given input is a character or a positive int

I want to know how to keep taking inputs from keyboard with this condition: If the given input is a positive number, it keeps going with the code If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. About negative and positive inputs the code i wrote works great, but it bugs out when I put a letter. The check I tried is the following

chk=isalpha(n);
while(!chk || n<0)
{
    printf("Inserire un intero positivo \n");
    scanf("%d", &n);
    chk=isalpha(n);
}
printf("%d\n%d\n", t1, t2);

In this case if I put a negative number it works correctly, but if I type a letter the printf loops. I also tried while(isalpha(n) || n<0) And a bunch of other pieces of code I'll skip for you. Please help me figure this out

1 answer

  • answered 2018-10-11 19:17 kiran Biradar

    You can check return value of scanf in case of char it returns 0 along with that you need to clear the buffer to stop scanf consuming the same character.

    Example:

    int ret = 0;
    do
    {
         char c;
         while ((c = getchar()) != '\n' && c != EOF) { } /* to clear the bad characters*/
    
         printf("Inserire un intero positivo \n");
         ret = scanf("%d", &n);
    }while(!ret || n<0);